"""TUI Entry Point - Launch LAIDA Mission Control.

Contract: CNT-TUI-MAIN-001
Traceability: UX-001, UI-002

This module provides the entry point for the TUI mode.
It is registered as a CLI command: `laida tui`
"""

import os
import sys
from pathlib import Path

import click

from laida_cli.services.detect_state import DetectStateService
from laida_cli.ui import console


def _supports_advanced_tui() -> bool:
    """Check if the terminal supports the full TUI experience.

    Returns:
        True if terminal supports advanced TUI features
    """
    # Check if running in a TTY
    if not sys.stdin.isatty():
        return False

    # Check terminal capabilities
    term = os.environ.get("TERM", "")
    colorterm = os.environ.get("COLORTERM", "")

    # Support for 256 colors or truecolor
    supports_colors = (
        "256color" in term
        or "truecolor" in colorterm
        or colorterm == "24bit"
        or term in ("xterm-256color", "screen-256color", "tmux-256color")
    )

    return supports_colors


def _show_simple_status(project_path: Path) -> None:
    """Show project status in simple mode.

    Args:
        project_path: Path to LAIDA project
    """
    state_service = DetectStateService()
    state = state_service.detect(project_path)

    console.header("Project Status")
    console.print(f"Path: {project_path}")
    console.print()

    if state.is_complete:
        console.success("Project complete! All 20 steps finished.")
    elif not state.has_started:
        console.warning("Project not started")
        console.hint("Run 'laida run 0 0' to begin")
    else:
        completed = (state.last_completed_phase or 0) * 4 + (state.last_completed_step or 0) + 1
        console.print(f"Progress: {completed}/20 steps completed")
        step_name = state_service.get_step_name(state.next_phase, state.next_step)
        console.print(f"Next: Phase {state.next_phase} Step {state.next_step} ({step_name})")


def _launch_simple_mode(project_path: Path) -> None:
    """Launch simplified fallback mode for limited terminals.

    Provides a basic interactive menu using Rich.

    Args:
        project_path: Path to LAIDA project
    """
    console.warning("Terminal has limited capabilities. Using simplified mode.")
    console.print()
    console.hint("For the full TUI experience, use a modern terminal like:")
    console.muted("  - Windows Terminal")
    console.muted("  - iTerm2 (macOS)")
    console.muted("  - Any terminal with 256-color support")
    console.print()

    # Show status
    _show_simple_status(project_path)
    console.print()

    # Show available commands
    console.header("Available Commands")
    console.muted("  laida status    - Show project status")
    console.muted("  laida run N M   - Execute Phase N Step M")
    console.muted("  laida validate  - Validate artifacts")
    console.muted("  laida tui --force  - Force TUI mode")


def launch_tui(project_path: Path) -> None:
    """Launch the LAIDA Mission Control TUI.

    Args:
        project_path: Path to LAIDA project

    Raises:
        SystemExit: If TUI cannot be launched
    """
    # Check terminal capabilities
    if not _supports_advanced_tui():
        _launch_simple_mode(project_path)
        return

    # Import TUI app (lazy import to avoid loading Textual unnecessarily)
    from laida_cli.tui.app import TUIApp

    # Launch the TUI
    app = TUIApp(project_path=project_path)
    app.run()


@click.command("tui")
@click.option(
    "--path",
    "-p",
    type=click.Path(exists=True),
    default=".",
    help="Path to LAIDA project (default: current directory)",
)
@click.option(
    "--force",
    is_flag=True,
    help="Force TUI mode even if terminal capabilities are limited",
)
def tui_command(path: str, force: bool) -> None:
    """Launch the Mission Control TUI interface.

    The TUI provides a dashboard-style interface with:
    - Real-time Claude output streaming
    - Project file tree with live updates
    - Git status monitoring
    - Session telemetry

    Requires a terminal with 256-color support for the best experience.

    Examples:
        laida tui              Launch TUI in current directory
        laida tui -p ./myproj  Launch TUI for specific project
    """
    project_path = Path(path).resolve()

    # Check if LAIDA project
    if not (project_path / ".laida").exists():
        console.error("Not a LAIDA project. Run 'laida init' first.")
        raise SystemExit(1)

    if force:
        # Force TUI mode
        from laida_cli.tui.app import TUIApp

        app = TUIApp(project_path=project_path)
        app.run()
    else:
        launch_tui(project_path)
