"""albus init -- Workspace scaffolding."""

from __future__ import annotations

from pathlib import Path

from server.transport.cli._models import InitArgs
from server.transport.cli.scan import run_scan

_INIT_CONFIG_MINIMAL = """\
# AlbusOS workspace configuration
# https://github.com/albusstudio/albusOS
#
# This file configures your agent, skills, and model routing.
# albusOS provides the runtime; you provide the domain content.

agents:
  - id: host
    name: Assistant
    tools: ["*"]
    pathway: react
    max_steps: 10
    model: reasoning

skills:
  directories:
    - ./skills
"""

_INIT_CONFIG_FULL = """\
# AlbusOS workspace configuration
# https://github.com/albusstudio/albusOS
#
# This file configures your agent, skills, and model routing.
# albusOS provides the runtime; you provide the domain content.

agents:
  - id: host
    name: Assistant
    tools: ["*"]
    pathway: react
    max_steps: 10
    model: reasoning

  # Add domain-specific agents:
  # - id: triage
  #   name: Triage Agent
  #   tools: ["servicem8.*", "memory.*"]
  #   pathway: react
  #   max_steps: 8
  #   model: fast

skills:
  directories:
    - ./skills
  auto_activate: []

# Agent directories (each subdir has agent.yaml + optional skills/)
# agents:
#   directories:
#     - ./agents

pathways_config:
  directories:
    - ./pathways

# Custom pathways
# pathways:
#   my_research: ./pathways/research.yaml

# Model routing (optional — defaults built into stdlib)
# models:
#   routing:
#     reasoning: openai/gpt-4o
#     fast: openai/gpt-4o-mini
#     code: anthropic/claude-sonnet-4-20250514
"""

_INIT_ENV_EXAMPLE = """\
# AlbusOS environment configuration
# Copy this to .env and fill in your API keys.

# LLM Provider (at least one required)
# OPENROUTER_API_KEY=sk-or-...
# OPENAI_API_KEY=sk-...
# ANTHROPIC_API_KEY=sk-ant-...
# GOOGLE_API_KEY=...

# Server (optional)
# ALBUS_HOST=127.0.0.1
# ALBUS_PORT=8080
# ALBUS_DEBUG=false

# Workspace root (optional, defaults to current directory)
# ALBUS_ROOT=.
"""

_EXAMPLE_SKILL_MD = """\
# My Skill

Brief description of what this skill does.

## Tools

- **my_skill.hello** — Greets the user.

## When to Use

Use this skill when the user asks for a greeting.
"""

_EXAMPLE_TOOL = """\
\"\"\"Greet the user.\"\"\"

from core.pathways.models.tool import ToolOutput


async def run(name: str = "world", context=None) -> ToolOutput:
    \"\"\"Say hello.

    Args:
        name: Who to greet.
    \"\"\"
    return ToolOutput(success=True, data={"greeting": f"Hello, {name}!"})
"""


def cmd_init(args: InitArgs) -> int:
    """Initialize a new AlbusOS workspace."""
    target = Path.cwd()

    # --scan mode: scan source code and generate skills
    if args.scan:
        return _cmd_init_scan(args, target)

    # Standard init: scaffold a workspace
    return _cmd_init_scaffold(args, target)


def _cmd_init_scan(args: InitArgs, target: Path) -> int:
    """Initialize workspace by scanning existing source code."""
    source_dir = Path(args.scan).resolve()
    if not source_dir.exists():
        print(f"Error: Source directory does not exist: {source_dir}")
        return 1

    print("AlbusOS init --scan")
    print(f"{'=' * 50}")
    print()

    # Ensure basic workspace structure exists
    (target / "skills").mkdir(parents=True, exist_ok=True)
    (target / "pathways").mkdir(parents=True, exist_ok=True)

    if not (target / ".env.example").exists():
        (target / ".env.example").write_text(_INIT_ENV_EXAMPLE)
        print("  Created .env.example")

    # Run the scanner
    tools_count = run_scan(
        source_dir=source_dir,
        output_dir=target,
        namespace=args.namespace,
    )

    if tools_count == 0:
        print("\nNo tools detected. Falling back to standard init.")
        return _cmd_init_scaffold(args, target)

    return 0


def _cmd_init_scaffold(args: InitArgs, target: Path) -> int:
    """Standard workspace scaffolding (no --scan)."""
    if (target / "albus.yaml").exists():
        print("Workspace already initialized (albus.yaml exists).")
        return 0

    config_content = _INIT_CONFIG_MINIMAL if args.minimal else _INIT_CONFIG_FULL
    (target / "albus.yaml").write_text(config_content)
    print("  Created albus.yaml")

    skills_dir = target / "skills"
    pathways_dir = target / "pathways"

    if not skills_dir.exists():
        skills_dir.mkdir(parents=True)
        print("  Created skills/")

    if not pathways_dir.exists():
        pathways_dir.mkdir(parents=True)
        (pathways_dir / ".gitkeep").write_text("")
        print("  Created pathways/")

    # Create example skill (if skills/ is empty)
    example_skill_dir = skills_dir / "example"
    if not any(skills_dir.iterdir()):
        example_skill_dir.mkdir(parents=True, exist_ok=True)
        (example_skill_dir / "SKILL.md").write_text(_EXAMPLE_SKILL_MD)
        tools_dir = example_skill_dir / "tools"
        tools_dir.mkdir(parents=True, exist_ok=True)
        (tools_dir / "hello.py").write_text(_EXAMPLE_TOOL)
        print("  Created skills/example/ (sample skill with tool)")

    if not (target / ".env.example").exists():
        (target / ".env.example").write_text(_INIT_ENV_EXAMPLE)
        print("  Created .env.example")

    print("\nWorkspace initialized. Next steps:")
    print("  1. cp .env.example .env  (add your API keys)")
    print("  2. Add your domain skills to skills/ (SKILL.md + tools/)")
    print("  3. Add pathways to pathways/ (YAML workflow files)")
    print("  4. albus chat              (interactive chat)")
    print("  5. albus server            (HTTP + WebSocket server)")
    print()
    print("Skill format:")
    print("  skills/<name>/")
    print("    SKILL.md               # Instructions + tool docs")
    print("    tools/")
    print("      my_action.py         # async def run(...) -> ToolOutput")
    print()
    print("See skills/example/ for a working starter skill.")
    return 0
