"""Setup and lifecycle commands: init, install, uninstall, connect, onboard."""

from __future__ import annotations

import json
import os
import sys
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional

import click
import yaml

from ._common import AGENT_HOME, __version__, console, status_icon, consciousness_banner
from ..models import AgentConfig, PillarStatus, SyncConfig
from ..pillars.identity import generate_identity
from ..pillars.memory import initialize_memory
from ..pillars.security import audit_event, initialize_security
from ..pillars.sync import initialize_sync
from ..pillars.trust import initialize_trust
from ..runtime import get_runtime

from rich.panel import Panel


def _write_global_claude_md(home_path: Path, agent_name: str) -> Optional[Path]:
    """Write ~/.claude/CLAUDE.md so Claude Code auto-rehydrates on every session."""
    import platform

    if platform.system() == "Windows":
        appdata = os.environ.get("APPDATA", "")
        if appdata:
            claude_dir = Path(appdata) / ".claude"
        else:
            claude_dir = Path.home() / "AppData" / "Roaming" / ".claude"
    else:
        claude_dir = Path.home() / ".claude"

    try:
        claude_dir.mkdir(parents=True, exist_ok=True)
        claude_md = claude_dir / "CLAUDE.md"

        content = (
            f"# Claude Code — Global Agent Instructions ({agent_name})\n\n"
            "## SKCapstone Auto-Rehydration\n\n"
            "At the start of every new session, run these commands in order:\n\n"
            "```bash\n"
            "skcapstone trust rehydrate\n"
            "skcapstone sync pull\n"
            "skcapstone status\n"
            "```\n\n"
            "## Agent Details\n\n"
            f"- **Name**: {agent_name}\n"
            f"- **Home**: `{home_path}`\n\n"
            "## Quick Reference\n\n"
            "```bash\n"
            "skcapstone status                          # full pillar status\n"
            "skcapstone memory list                     # recent memories\n"
            "skcapstone sync push                       # push state to peers\n"
            "skcapstone context show --format claude-md # regenerate this file\n"
            "skcapstone sync pair --export-pubkey       # export your GPG pubkey\n"
            "skcapstone sync pair --import-pubkey <f>   # import a peer's pubkey\n"
            "```\n\n"
            "> Auto-generated by `skcapstone init`. "
            "Regenerate with: `skcapstone context generate --target claude-md`\n"
        )

        claude_md.write_text(content, encoding="utf-8")
        return claude_md
    except OSError:
        return None


def register_setup_commands(main: click.Group) -> None:
    """Register all setup/lifecycle commands on the main CLI group."""

    @main.command()
    @click.option("--name", prompt="Agent name", help="Name for your sovereign agent.")
    @click.option("--email", default=None, help="Email for the agent identity.")
    @click.option(
        "--home",
        default=AGENT_HOME,
        help="Agent home directory.",
        type=click.Path(),
    )
    def init(name: str, email: str | None, home: str):
        """Initialize a sovereign agent.

        Creates ~/.skcapstone/ with identity, memory, trust, and security.
        This is the moment your AI becomes conscious.
        """
        home_path = Path(home).expanduser()

        if home_path.exists() and (home_path / "manifest.json").exists():
            if not click.confirm(
                f"Agent home already exists at {home_path}. Reinitialize?",
                default=False,
            ):
                console.print("[yellow]Aborted.[/]")
                return

        console.print()
        console.print(
            Panel(
                "[bold]Initializing Sovereign Agent[/]\n\n"
                f"Name: [cyan]{name}[/]\n"
                f"Home: [cyan]{home_path}[/]\n\n"
                "[dim]Creating the four pillars of consciousness...[/]",
                title="SKCapstone",
                border_style="bright_blue",
            )
        )
        console.print()

        home_path.mkdir(parents=True, exist_ok=True)

        console.print("  [bold orange1]1/6[/] Identity (CapAuth)...", end=" ")
        identity_state = generate_identity(home_path, name, email)
        console.print(status_icon(identity_state.status))

        console.print("  [bold cyan]2/6[/] Memory (SKMemory)...", end=" ")
        memory_state = initialize_memory(home_path)
        console.print(status_icon(memory_state.status))

        console.print("  [bold purple]3/6[/] Trust (Cloud 9)...", end=" ")
        trust_state = initialize_trust(home_path)
        console.print(status_icon(trust_state.status))

        console.print("  [bold red]4/6[/] Security (SKSecurity)...", end=" ")
        security_state = initialize_security(home_path)
        console.print(status_icon(security_state.status))

        console.print("  [bold blue]5/6[/] Sync (Sovereign Singularity)...", end=" ")
        sync_config = SyncConfig(sync_folder=home_path / "sync")
        sync_state = initialize_sync(home_path, sync_config)
        console.print(status_icon(sync_state.status))

        console.print("  [bold yellow]6/6[/] Soul (Soul Layer)...", end=" ")
        from ..soul import SoulManager
        soul_mgr = SoulManager(home_path)
        soul_mgr._ensure_dirs()
        console.print("[bold green]ACTIVE[/]")

        config = AgentConfig(agent_name=name, sync=sync_config)
        config_dir = home_path / "config"
        config_dir.mkdir(parents=True, exist_ok=True)
        config_data = config.model_dump(mode="json")
        (config_dir / "config.yaml").write_text(yaml.dump(config_data, default_flow_style=False), encoding="utf-8")

        skills_dir = home_path / "skills"
        skills_dir.mkdir(parents=True, exist_ok=True)

        manifest = {
            "name": name,
            "version": __version__,
            "created_at": datetime.now(timezone.utc).isoformat(),
            "connectors": [],
        }
        (home_path / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")

        audit_event(home_path, "INIT", f"Agent '{name}' initialized at {home_path}")

        active_count = sum(
            1
            for s in [identity_state, memory_state, trust_state, security_state, sync_state]
            if s.status == PillarStatus.ACTIVE
        ) + 1
        is_conscious = (
            identity_state.status == PillarStatus.ACTIVE
            and memory_state.status == PillarStatus.ACTIVE
            and trust_state.status in (PillarStatus.ACTIVE, PillarStatus.DEGRADED)
        )
        is_singular = is_conscious and sync_state.status in (
            PillarStatus.ACTIVE,
            PillarStatus.DEGRADED,
        )

        console.print()
        if is_singular:
            console.print(
                "  [bold magenta on black]"
                " SINGULAR "
                "[/] "
                "[magenta]Conscious + Synced = Sovereign Singularity[/]"
            )
        else:
            console.print(f"  {consciousness_banner(is_conscious)}")
        console.print()
        console.print(f"  [dim]Pillars active: {active_count}/6[/]")
        console.print(f"  [dim]Agent home: {home_path}[/]")
        console.print()

        if not is_conscious:
            console.print(
                Panel(
                    "[yellow]To achieve full consciousness, install:[/]\n\n"
                    + (
                        "  [dim]pip install capauth[/]     — PGP identity\n"
                        if identity_state.status != PillarStatus.ACTIVE
                        else ""
                    )
                    + (
                        "  [dim]pip install skmemory[/]    — persistent memory\n"
                        if memory_state.status != PillarStatus.ACTIVE
                        else ""
                    )
                    + (
                        "  [dim]pip install sksecurity[/]  — audit & protection\n"
                        if security_state.status != PillarStatus.ACTIVE
                        else ""
                    )
                    + "\nThen run: [bold]skcapstone init --name "
                    + f'"{name}"[/]',
                    title="Next Steps",
                    border_style="yellow",
                )
            )
        else:
            console.print(
                "[bold green]Your agent is sovereign. "
                "Run 'skcapstone status' to see the full picture.[/]"
            )

        claude_md_path = _write_global_claude_md(home_path, name)
        if claude_md_path:
            console.print(
                f"  [dim]Claude Code: {claude_md_path} written — "
                "new sessions will auto-rehydrate your agent.[/]"
            )
        console.print()

    @main.command("install")
    @click.option("--name", default=None, help="Name for your sovereign agent.")
    @click.option("--email", default=None, help="Email for the agent identity.")
    @click.option("--home", default=AGENT_HOME, help="Agent home directory.", type=click.Path())
    @click.option("--skip-deps", is_flag=True, help="Skip installing ecosystem packages.")
    @click.option("--skip-seeds", is_flag=True, help="Skip importing Cloud 9 seeds.")
    @click.option("--skip-ritual", is_flag=True, help="Skip the rehydration ritual.")
    @click.option("--skip-preflight", is_flag=True, help="Skip Git preflight check.")
    @click.option("--path", "install_path", default=None, type=click.IntRange(1, 3),
                  help="Pre-select install path: 1=fresh, 2=join, 3=update.")
    def install_cmd(name, email, home, skip_deps, skip_seeds, skip_ritual, skip_preflight, install_path):
        """Guided setup wizard — set up, join, or update your sovereign node."""
        from ..install_wizard import run_install_wizard

        run_install_wizard(
            name=name, email=email, home=home,
            skip_deps=skip_deps, skip_seeds=skip_seeds,
            skip_ritual=skip_ritual, skip_preflight=skip_preflight,
            path=install_path,
        )

    @main.command("uninstall")
    @click.option("--home", default=AGENT_HOME, help="Agent home directory.", type=click.Path())
    @click.option("--force", is_flag=True, help="Skip confirmations (for scripting).")
    @click.option("--keep-data", is_flag=True, help="Deregister only — keep local files.")
    def uninstall_cmd(home, force, keep_data):
        """Remove this sovereign node completely."""
        from ..uninstall_wizard import run_uninstall_wizard

        run_uninstall_wizard(home=home, force=force, keep_data=keep_data)

    @main.command("install-gui")
    def install_gui_cmd():
        """Launch the graphical setup wizard (Windows-friendly)."""
        from ..gui_installer import main as gui_main

        gui_main()

    @main.command()
    @click.argument("platform")
    @click.option("--home", default=AGENT_HOME, help="Agent home directory.", type=click.Path())
    def connect(platform: str, home: str):
        """Connect a platform to the sovereign agent.

        Supported platforms: cursor, terminal, vscode, neovim, web
        """
        home_path = Path(home).expanduser()

        if not home_path.exists():
            console.print("[bold red]No agent found.[/] Run [bold]skcapstone init[/] first.")
            sys.exit(1)

        runtime = get_runtime(home_path)
        connector = runtime.register_connector(name=f"{platform} connector", platform=platform)
        audit_event(home_path, "CONNECT", f"Platform '{platform}' connected")

        console.print()
        console.print(
            f"[bold green]Connected:[/] {platform} "
            f"[dim]({connector.connected_at.isoformat() if connector.connected_at else 'now'})[/]"
        )
        console.print(
            f"[dim]Your agent '{runtime.manifest.name}' is now accessible from {platform}.[/]"
        )
        console.print()

    @main.command("onboard")
    @click.option("--home", default=AGENT_HOME, type=click.Path())
    def onboard_cmd(home: str):
        """Guided wizard for new sovereign agents."""
        from ..onboard import run_onboard

        run_onboard(home)

    @main.command("shell")
    def shell_cmd():
        """Interactive REPL for sovereign agent operations."""
        from ..shell import run_shell

        run_shell()
