import typer
import os
from pathlib import Path
from rich.console import Console

app = typer.Typer(help="Lár: The PyTorch for Agents - CLI Tool")
new_app = typer.Typer(help="Create new Lár projects")
app.add_typer(new_app, name="new")
console = Console()

TEMPLATE_AGENT_PY = """from lar import GraphState, LLMNode, node
from dotenv import load_dotenv
import os

load_dotenv()

# 1. Define Nodes (using the new @node decorator where appropriate!)
@node(output_key="summary")
def simple_processor(state):
    print("Processing task...")
    return f"Processed: {state.get('input')}"

# Or use standard LLMNode
start_node = LLMNode(
    model_name="gemini/gemini-2.5-flash", 
    prompt_template="Answer this: {input}",
    output_key="response",
    next_node=None
)

# 2. State
initial_state = {"input": "Hello Lár!"}

# 3. Execution (Standard Boilerplate)
if __name__ == "__main__":
    from lar import GraphExecutor
    print("Starting Agent...")
    executor = GraphExecutor()
    # Run simple graph
    # Connect nodes manually if needed, or just run single node for demo
    for step in executor.run_step_by_step(start_node, initial_state):
        print(step)
"""

TEMPLATE_PYPROJECT_TOML = """[tool.poetry]
name = "{project_name}"
version = "0.1.0"
description = "A Lár Agent"
authors = ["Your Name <you@example.com>"]
readme = "README.md"

[tool.poetry.dependencies]
python = "^3.11"
lar-engine = "^1.4.0" 
python-dotenv = "^1.0.0"
typer = "^0.12.0"
click = "<8.1.0"

[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
"""

TEMPLATE_ENV = """# API Keys
GEMINI_API_KEY=""
OPENAI_API_KEY=""
ANTHROPIC_API_KEY=""
"""

@new_app.command("agent")
def create_agent(name: str):
    """
    Scaffold a new Lár agent project.
    
    Usage: lar new agent my-agent
    """
    project_path = Path(name)
    
    if project_path.exists():
        console.print(f"[bold red]Error:[/bold red] Directory '{name}' already exists.")
        raise typer.Exit(code=1)
    
    # 1. Create Directory
    project_path.mkdir(parents=True)
    console.print(f"[green]Created directory:[/green] {name}")
    
    # 2. Create agent.py
    with open(project_path / "agent.py", "w") as f:
        f.write(TEMPLATE_AGENT_PY)
        
    # 3. Create pyproject.toml
    with open(project_path / "pyproject.toml", "w") as f:
        f.write(TEMPLATE_PYPROJECT_TOML.format(project_name=name))
        
    # 4. Create .env
    with open(project_path / ".env", "w") as f:
        f.write(TEMPLATE_ENV)

    # 5. Create README.md
    with open(project_path / "README.md", "w") as f:
        f.write(f"# {name}\n\nGenerated by Lár CLI.")
        
    console.print(f"[bold green]Success![/bold green] Created new agent in '{name}'.")
    console.print(f"\nTo get started:\n  cd {name}\n  poetry install\n  python agent.py")

if __name__ == "__main__":
    app()
