"""nestdx run — launch a tool within the active session."""

from __future__ import annotations

from pathlib import Path

import click

from nestdx.adapters import ADAPTER_REGISTRY, resolve_adapter
from nestdx.adapters.cursor import CursorAdapter
from nestdx.config.parser import load_config
from nestdx.config.schema import ToolConfig
from nestdx.policy.engine import PolicyEngine
from nestdx.session.manager import NoActiveSessionError, SessionManager
from nestdx.session.models import ToolRun
from nestdx.utils.console import console


@click.command(
    context_settings={"ignore_unknown_options": True, "allow_extra_args": True},
)
@click.argument("tool", required=False)
@click.pass_context
def run_cmd(ctx: click.Context, tool: str | None):
    """Run a tool within the active session.

    \b
    Examples:
      nestdx run claude-code
      nestdx run -- pytest -x
      nestdx run -- echo hello
    """
    project_root = Path.cwd()
    extra_args: list[str] = ctx.args

    # Load config
    try:
        config = load_config()
    except Exception as e:
        console.print(f"[red]Error:[/red] {e}")
        raise SystemExit(1)

    # Verify active session
    manager = SessionManager(config, project_root)
    try:
        session = manager.get_active()
        if session is None:
            raise NoActiveSessionError("No active session.")
    except NoActiveSessionError:
        console.print("[red]Error:[/red] No active session. Run `nestdx start` first.")
        raise SystemExit(1)

    # Resolve adapter
    if tool is None and not extra_args:
        console.print("[red]Error:[/red] Specify a tool name or use `nestdx run -- <command>`.")
        raise SystemExit(1)

    if tool and tool == "--":
        # `nestdx run -- cmd args` — Click may pass "--" as the tool
        tool = None

    if tool is None:
        # Generic adapter: everything in extra_args is the command
        if not extra_args:
            console.print("[red]Error:[/red] No command provided after `--`.")
            raise SystemExit(1)
        adapter = resolve_adapter(None, command=extra_args)
        extra_args = []
        tool_config = ToolConfig()
    elif tool in ADAPTER_REGISTRY:
        # Named tool adapter
        adapter = resolve_adapter(tool)
        tool_config = config.tools.get(tool, ToolConfig())

        # Pre-run policy check: is tool enabled?
        engine = PolicyEngine(config, project_root=project_root)
        violation = engine.check_pre_run(tool)
        if violation:
            console.print(f"[red]Error:[/red] {violation.message}")
            raise SystemExit(1)
    else:
        # Not a known adapter — treat tool + extra_args as a generic command
        adapter = resolve_adapter(tool, command=[tool] + extra_args)
        extra_args = []
        tool_config = ToolConfig()

    # Check session duration limit
    exceeded, duration_msg = manager.check_session_duration(session)
    if exceeded:
        console.print(f"[red]Error:[/red] {duration_msg}")
        console.print("Run `nestdx stop` to end the session.")
        raise SystemExit(1)

    # Inject watcher for Cursor adapter
    if isinstance(adapter, CursorAdapter) and manager._watcher:
        adapter._watcher = manager._watcher

    # Container mode: exec inside container instead of local subprocess
    if manager._container is not None and manager._container.is_running:
        cmd = adapter.resolve_command(tool_config) + extra_args
        console.print(f"[cyan]Launching {adapter.name} in container...[/cyan]")

        from datetime import datetime, timezone

        start_time = datetime.now(timezone.utc)
        result = manager._container.exec_cmd(cmd)
        tool_run = ToolRun(
            tool=adapter.name,
            command=" ".join(cmd),
            start_time=start_time,
            end_time=datetime.now(timezone.utc),
            exit_code=result.returncode,
        )
        manager.add_tool_run(tool_run)
    else:
        # Validate tool is installed (local mode only)
        if not adapter.validate():
            cmd_name = tool or (extra_args[0] if extra_args else "command")
            console.print(f"[red]Error:[/red] '{cmd_name}' is not installed or not on PATH.")
            console.print(f"  [dim]{adapter.install_hint}[/dim]")
            raise SystemExit(1)

        # Run locally
        console.print(f"[cyan]Launching {adapter.name}...[/cyan]")
        tool_run = adapter.run(tool_config, extra_args)

        # Log tool run to session
        manager.add_tool_run(tool_run)

    # Summary
    if tool_run.exit_code == 0:
        console.print(f"[green]Tool exited cleanly[/green] (code {tool_run.exit_code}).")
    else:
        console.print(f"[yellow]Tool exited[/yellow] with code {tool_run.exit_code}.")
