"""nestdx start — begin a new session."""

from __future__ import annotations

from pathlib import Path

import click

from nestdx.config.parser import load_config
from nestdx.policy.engine import PolicyEngine
from nestdx.runtime.container import NoContainerRuntimeError
from nestdx.session.manager import ActiveSessionExistsError, SessionManager, StaleSessionError
from nestdx.utils.console import console


@click.command()
@click.option("--tool", "-t", default=None, help="Pre-select a tool (validates against config).")
@click.option("--dry-run", is_flag=True, help="Validate config without starting a session.")
@click.option("--local", is_flag=True, help="Force local mode even with environment config.")
@click.option("--container", is_flag=True, help="Require container mode (fail if no environment config).")
@click.option("--force", is_flag=True, help="Force-stop any existing session before starting.")
def start_cmd(tool: str | None, dry_run: bool, local: bool, container: bool, force: bool):
    """Start a new NestDX session."""
    project_root = Path.cwd()

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

    # Validate --container flag
    if container and config.environment is None:
        console.print(
            "[red]Error:[/red] --container requires an `environment:` block in nestdx.yaml."
        )
        raise SystemExit(1)

    # Validate tool if specified
    if tool:
        tool_config = config.tools.get(tool)
        if tool_config is None:
            console.print(f"[red]Error:[/red] Tool '{tool}' not found in config.")
            raise SystemExit(1)
        if not tool_config.enabled:
            reason = f" ({tool_config.reason})" if tool_config.reason else ""
            console.print(f"[red]Error:[/red] Tool '{tool}' is disabled{reason}.")
            raise SystemExit(1)

    if dry_run:
        console.print("[green]Config is valid.[/green]")
        console.print(f"  Project: {config.name}")
        enabled_tools = [name for name, tc in config.tools.items() if tc.enabled]
        console.print(f"  Enabled tools: {', '.join(enabled_tools) or 'none'}")
        is_container = config.environment is not None and not local
        if is_container:
            console.print(f"  Container: {config.environment.base}")
        else:
            console.print("  Mode: local")
        # Network policy info
        network = config.policies.network
        if network.block_all_other_egress:
            if is_container:
                domains = ", ".join(network.allowed_domains) or "none"
                console.print(f"  Network: egress restricted — allowed: {domains}")
            else:
                console.print(
                    "  [yellow]Network: egress policy configured but requires container mode[/yellow]"
                )
        return

    manager = SessionManager(config, project_root, force_local=local)

    try:
        session = manager.start(force=force)
    except StaleSessionError as e:
        console.print(f"[yellow]Warning:[/yellow] {e}")
        raise SystemExit(1)
    except ActiveSessionExistsError as e:
        console.print(f"[red]Error:[/red] {e}")
        raise SystemExit(1)

    console.print(f"[green]Session started:[/green] {session.id}")
    if session.git_snapshot:
        console.print(f"  Branch: {session.git_snapshot.branch}")
        console.print(f"  HEAD: {session.git_snapshot.head_sha[:8]}")
        if session.git_snapshot.dirty_files:
            console.print(f"  Dirty files: {len(session.git_snapshot.dirty_files)}")
    else:
        console.print("  [yellow]Not a git repo — git features disabled.[/yellow]")

    # Check network policy warning (local mode with egress policy)
    engine = PolicyEngine(config, project_root=project_root)
    net_warning = engine.check_network_policy(container_mode=manager.container_mode)
    if net_warning:
        console.print(f"  [yellow]Warning:[/yellow] {net_warning.message}")

    # Start container if in container mode
    if manager.container_mode:
        try:
            container_id = manager.start_container(session.id)
            console.print(f"  [cyan]Container started:[/cyan] {container_id}")
        except NoContainerRuntimeError as e:
            console.print(f"[red]Error:[/red] {e}")
            manager.abort()
            raise SystemExit(1)
        except Exception as e:
            console.print(f"[red]Error:[/red] Container setup failed: {e}")
            manager.abort()
            raise SystemExit(1)

        # Display network egress info
        network = config.policies.network
        if network.block_all_other_egress:
            domains = ", ".join(network.allowed_domains) or "none"
            console.print(f"  [cyan]Network: egress restricted[/cyan] — allowed: {domains}")

    # Start file watcher
    if manager.start_watcher():
        console.print("  [cyan]File watcher active[/cyan]")
    else:
        console.print("  [yellow]File watcher unavailable — changes detected via git diff only[/yellow]")

    enabled_tools = [name for name, tc in config.tools.items() if tc.enabled]
    console.print(f"  Tools: {', '.join(enabled_tools) or 'none'}")
    console.print(f"\nRun [cyan]nestdx run {tool or '<tool>'}[/cyan] to launch a tool.")
