"""nestdx stop — finalize the active 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.session.manager import NoActiveSessionError, SessionManager
from nestdx.session.storage import save_session
from nestdx.utils.console import CHANGE_COLORS, console, format_duration, print_violations


@click.command()
@click.option("--force", is_flag=True, help="Force-stop a stale session.")
def stop_cmd(force: bool):
    """Stop the active NestDX session."""
    project_root = Path.cwd()

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

    manager = SessionManager(config, project_root)

    if force:
        session = manager.force_stop()
        if session is None:
            console.print("[yellow]No active session to force-stop.[/yellow]")
            return
        console.print(f"[yellow]Force-stopped session:[/yellow] {session.id}")
        return

    try:
        session = manager.stop()
    except NoActiveSessionError:
        console.print("[red]Error:[/red] No active session. Run `nestdx start` first.")
        raise SystemExit(1)

    # Run policy checks on changed files
    engine = PolicyEngine(config, project_root=project_root)
    violations = engine.check_post_session(session.file_changes, project_root)
    if violations:
        session.violations = violations
        sessions_dir = project_root / config.tracking.session_dir
        save_session(session, sessions_dir)

    # Print summary
    console.print(f"[green]Session stopped:[/green] {session.id}")
    console.print(f"  Duration: {format_duration(session.duration_seconds)}")

    console.print(f"  Files changed: {len(session.file_changes)}")
    for fc in session.file_changes:
        color = CHANGE_COLORS.get(fc.change_type, "white")
        console.print(f"    [{color}]{fc.change_type:>8}[/{color}] {fc.path}")

    console.print(f"  Tool runs: {len(session.tool_runs)}")
    print_violations(session.violations)
