"""SDK Scaffolding — generate boilerplate for new agents and tools.

Generates ready-to-run Python files with proper SDK decorators.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from pathlib import Path

# ---------------------------------------------------------------------------
# Agent scaffold
# ---------------------------------------------------------------------------

_AGENT_TEMPLATE = '''"""Agent: {name} — {description}

Auto-generated by Cognithor SDK.
"""

from cognithor.sdk import agent, tool, hook


@tool(name="{name}_process", description="Process input for {name}")
async def process(text: str) -> str:
    """Process the given text."""
    return f"Processed: {{text}}"


@agent(
    name="{name}",
    description="{description}",
    tools=["{name}_process"],
    trigger_keywords={keywords},
    version="0.1.0",
)
class {class_name}:
    """Agent: {description}"""

    async def on_message(self, message: str) -> str:
        """Handle incoming messages."""
        return f"{{message}} — handled by {name}"


@hook("on_error")
async def handle_error(error: Exception) -> None:
    """Log errors from this agent."""
    print(f"[{name}] Error: {{error}}")
'''


def scaffold_agent(
    name: str,
    description: str = "",
    keywords: list[str] | None = None,
    output_dir: Path | None = None,
) -> str:
    """Generate a new agent Python file.

    Args:
        name: Agent name (snake_case).
        description: Short description.
        keywords: Trigger keywords.
        output_dir: Where to write the file. If None, returns content only.

    Returns:
        The generated Python source code.
    """
    class_name = "".join(w.capitalize() for w in name.split("_")) + "Agent"
    content = _AGENT_TEMPLATE.format(
        name=name,
        description=description or f"{name} agent",
        class_name=class_name,
        keywords=keywords or [name],
    )

    if output_dir:
        output_dir.mkdir(parents=True, exist_ok=True)
        path = output_dir / f"{name}_agent.py"
        path.write_text(content, encoding="utf-8")

    return content


# ---------------------------------------------------------------------------
# Tool scaffold
# ---------------------------------------------------------------------------

_TOOL_TEMPLATE = '''"""Tool: {name} — {description}

Auto-generated by Cognithor SDK.
"""

from cognithor.sdk import tool


@tool(
    name="{name}",
    description="{description}",
    risk_level="{risk_level}",
    read_only={read_only},
)
async def {func_name}({params_str}) -> {return_type}:
    """{description}"""
    # TODO: Implement tool logic
    return {default_return}
'''


def scaffold_tool(
    name: str,
    description: str = "",
    params: dict[str, str] | None = None,
    return_type: str = "str",
    risk_level: str = "green",
    read_only: bool = False,
    output_dir: Path | None = None,
) -> str:
    """Generate a new tool Python file.

    Args:
        name: Tool name (snake_case).
        description: Short description.
        params: Parameter name → type mapping.
        return_type: Return type annotation.
        risk_level: Risk classification.
        read_only: Whether tool is read-only.
        output_dir: Where to write the file.

    Returns:
        The generated Python source code.
    """
    param_list = params or {"text": "str"}
    params_str = ", ".join(f"{k}: {v}" for k, v in param_list.items())

    default_returns = {
        "str": '"result"',
        "int": "0",
        "float": "0.0",
        "bool": "True",
        "dict": "{}",
        "list": "[]",
    }
    default_return = default_returns.get(return_type, '""')

    content = _TOOL_TEMPLATE.format(
        name=name,
        description=description or f"{name} tool",
        func_name=name.replace("-", "_"),
        params_str=params_str,
        return_type=return_type,
        risk_level=risk_level,
        read_only=read_only,
        default_return=default_return,
    )

    if output_dir:
        output_dir.mkdir(parents=True, exist_ok=True)
        path = output_dir / f"{name}_tool.py"
        path.write_text(content, encoding="utf-8")

    return content
