"""``albus init`` — scaffold a new AlbusOS workspace."""

from __future__ import annotations

from pathlib import Path
from typing import Annotated

import typer

from albusos.cli import app
from albusos.cli._helpers import err

_STARTER_AGENT = '''\
"""Starter agent — edit this file to customize."""

from albusos import agent

agent = agent(
    "{agent_id}",
    instructions="You are a helpful assistant.",
    tools=["*"],
)
'''


@app.command("init")
def init_cmd(
    root: Annotated[str, typer.Argument(help="Directory to initialize.")] = ".",
    agent_id: Annotated[
        str,
        typer.Option("--agent", "-a", help="ID for the starter agent."),
    ] = "assistant",
) -> None:
    """Scaffold a new AlbusOS workspace directory structure."""
    base = Path(root).resolve()

    dirs = [
        base / "agents",
        base / "pathways",
        base / "skills",
    ]

    created: list[str] = []
    for d in dirs:
        if not d.exists():
            d.mkdir(parents=True, exist_ok=True)
            created.append(str(d.relative_to(base)))

    # Write starter agent if agents/ is empty.
    agents_dir = base / "agents"
    agent_file = agents_dir / f"{agent_id}.py"
    if not any(agents_dir.glob("*.py")):
        agent_file.write_text(_STARTER_AGENT.format(agent_id=agent_id))
        created.append(str(agent_file.relative_to(base)))

    if created:
        err.print("[green]Workspace initialized:[/green]")
        for item in created:
            err.print(f"  + {item}")
    else:
        err.print("Workspace already initialized — nothing to create.")
