"""Status command - Show project status.

Contract: CNT-T4-CMD-003
Traceability: UI-002
"""

from pathlib import Path

import click

from laida_cli.services.detect_state import DetectStateService
from laida_cli.ui import LaidaConsole, Styles

console = LaidaConsole()


@click.command("status")
@click.option(
    "--path", "-p",
    type=click.Path(exists=True),
    default=".",
    help="Path to LAIDA project (default: current directory)",
)
@click.option(
    "--json", "as_json",
    is_flag=True,
    help="Output as JSON",
)
def status_command(path: str, as_json: bool) -> None:
    """Show current project status.

    Displays:
    - Last completed phase/step
    - Next phase/step to execute
    - Overall progress
    """
    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)

    # Detect state
    state_service = DetectStateService()
    state = state_service.detect(project_path)

    if as_json:
        import json
        output = {
            "project_path": str(project_path),
            "last_completed_phase": state.last_completed_phase,
            "last_completed_step": state.last_completed_step,
            "next_phase": state.next_phase,
            "next_step": state.next_step,
            "is_complete": state.is_complete,
        }
        console.print(json.dumps(output, indent=2))
        return

    # Display status table
    console.print()
    console.header("LAIDA Project Status")
    console.print(f"Path: {project_path}")
    console.print()

    table = console.status_table()

    if state.is_complete:
        table.add_row("Status", f"[{Styles.SUCCESS}]Complete[/{Styles.SUCCESS}]")
        table.add_row("Last Completed", "Phase 4 Step 3")
    elif not state.has_started:
        table.add_row("Status", f"[{Styles.WARNING}]Not Started[/{Styles.WARNING}]")
        table.add_row("Next Step", "Phase 0 Step 0")
    else:
        table.add_row("Status", f"[{Styles.INFO}]In Progress[/{Styles.INFO}]")
        table.add_row(
            "Last Completed",
            f"Phase {state.last_completed_phase} Step {state.last_completed_step}"
        )
        table.add_row(
            "Next Step",
            f"Phase {state.next_phase} Step {state.next_step}"
        )

    # Add progress bar
    total_steps = 20  # 5 phases * 4 steps
    completed_steps = 0
    if state.last_completed_phase is not None and state.last_completed_step is not None:
        completed_steps = (state.last_completed_phase * 4) + state.last_completed_step + 1

    progress_pct = (completed_steps / total_steps) * 100
    table.add_row("Progress", f"{progress_pct:.0f}% ({completed_steps}/{total_steps} steps)")

    console.print(table)

    if not state.is_complete:
        console.print()
        next_step_name = state_service.get_step_name(state.next_phase, state.next_step)
        console.hint(
            f"Run: laida run {state.next_phase} {state.next_step}  # {next_step_name}"
        )
