"""Command-line interface for Domain Vigil."""

import sys
from pathlib import Path
from typing import Optional

import click
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich import box

from domain_vigil import __version__
from domain_vigil.parsers.persona_parser import PersonaParser
from domain_vigil.core.models import Persona

console = Console()


@click.group()
@click.version_option(version=__version__)
def main() -> None:
    """Domain Vigil - Keeping watch over your domain knowledge.

    Bidirectional persona-based validation to prevent domain drift.
    """
    pass


@main.command()
@click.option(
    "--persona",
    "-p",
    required=True,
    type=click.Path(exists=True, path_type=Path),
    help="Path to persona YAML file"
)
@click.option(
    "--path",
    "-P",
    required=True,
    type=click.Path(exists=True, path_type=Path),
    help="Path to code to validate"
)
@click.option(
    "--output",
    "-o",
    type=click.Choice(["text", "json"]),
    default="text",
    help="Output format"
)
def validate(persona: Path, path: Path, output: str) -> None:
    """Validate code against persona deal-breakers.

    This command analyzes your code and checks for violations of
    the persona's deal-breakers.
    """
    try:
        # Parse persona
        console.print(f"[cyan]Loading persona from {persona}...[/cyan]")
        persona_obj = PersonaParser.parse_file(persona)

        console.print(Panel.fit(
            f"[bold]{persona_obj.name}[/bold]\n{persona_obj.description}",
            title="Persona",
            border_style="cyan"
        ))

        # Show deal-breakers
        table = Table(title="Deal-Breakers", box=box.ROUNDED)
        table.add_column("ID", style="cyan")
        table.add_column("Description", style="white")
        table.add_column("Severity", style="yellow")

        for db in persona_obj.deal_breakers:
            table.add_row(db.id, db.description, db.severity.value)

        console.print(table)

        # TODO: Implement actual validation
        console.print("\n[yellow]⚠ Validation not yet implemented[/yellow]")
        console.print("[dim]Phase 1 implementation in progress...[/dim]")

    except Exception as e:
        console.print(f"[red]Error: {e}[/red]", file=sys.stderr)
        sys.exit(1)


@main.command()
@click.option(
    "--persona",
    "-p",
    required=True,
    type=click.Path(exists=True, path_type=Path),
    help="Path to persona YAML file"
)
@click.option(
    "--path",
    "-P",
    required=True,
    type=click.Path(exists=True, path_type=Path),
    help="Path to code to learn from"
)
@click.option(
    "--output",
    "-o",
    type=click.Path(path_type=Path),
    help="Output path for updated persona (stdout if not specified)"
)
def learn(persona: Path, path: Path, output: Optional[Path]) -> None:
    """Learn validation patterns from codebase.

    This command uses LLM to analyze your codebase and learn what
    patterns are relevant to the persona's deal-breakers.

    The learned patterns must be reviewed and validated by you before
    they become active.
    """
    try:
        # Parse persona
        console.print(f"[cyan]Loading persona from {persona}...[/cyan]")
        persona_obj = PersonaParser.parse_file(persona)

        console.print(f"[cyan]Analyzing codebase at {path}...[/cyan]")

        # TODO: Implement learning
        console.print("\n[yellow]⚠ Learning not yet implemented[/yellow]")
        console.print("[dim]Phase 1 implementation in progress...[/dim]")

    except Exception as e:
        console.print(f"[red]Error: {e}[/red]", file=sys.stderr)
        sys.exit(1)


@main.command()
@click.argument("persona_file", type=click.Path(exists=True, path_type=Path))
def show(persona_file: Path) -> None:
    """Display a persona definition.

    Shows the complete persona including deal-breakers, abilities,
    and learned patterns.
    """
    try:
        persona_obj = PersonaParser.parse_file(persona_file)

        # Main info
        console.print(Panel.fit(
            f"[bold cyan]{persona_obj.name}[/bold cyan]\n\n{persona_obj.description}",
            title="Persona",
            border_style="cyan"
        ))

        # Deal-breakers
        if persona_obj.deal_breakers:
            table = Table(title="Deal-Breakers", box=box.ROUNDED, show_lines=True)
            table.add_column("ID", style="cyan", no_wrap=True)
            table.add_column("Description", style="white")
            table.add_column("Severity", style="yellow", no_wrap=True)
            table.add_column("Learned Patterns", style="dim")

            for db in persona_obj.deal_breakers:
                patterns = f"{len(db.learned_patterns)} pattern(s)" if db.learned_patterns else "None"
                table.add_row(db.id, db.description, db.severity.value, patterns)

            console.print(table)

        # Abilities
        if persona_obj.abilities:
            table = Table(title="Abilities", box=box.ROUNDED)
            table.add_column("ID", style="cyan")
            table.add_column("Description", style="white")

            for ab in persona_obj.abilities:
                table.add_row(ab.id, ab.description)

            console.print(table)

    except Exception as e:
        console.print(f"[red]Error: {e}[/red]", file=sys.stderr)
        sys.exit(1)


@main.command()
def init() -> None:
    """Initialize a new persona file.

    Creates a sample persona.yml in the current directory.
    """
    output_file = Path("persona.yml")

    if output_file.exists():
        console.print(f"[red]Error: {output_file} already exists[/red]", file=sys.stderr)
        sys.exit(1)

    sample_persona = """persona: my_persona
description: |
  Describe your persona here. What role do they play in your system?
  What matters most about their behavior?

deal_breakers:
  - id: example_dealbreaker
    description: "Describe what must never happen"
    severity: critical
    examples:
      - "Example violation scenario 1"
      - "Example violation scenario 2"

abilities:
  - id: example_ability
    description: "Describe what this persona can do"
    examples:
      - "Example action 1"

metadata:
  domain: your_domain
  created: 2026-02-08
  version: 1.0
"""

    output_file.write_text(sample_persona)
    console.print(f"[green]✓ Created {output_file}[/green]")
    console.print("\n[dim]Edit the file to define your persona, then run:[/dim]")
    console.print(f"[cyan]  domain-vigil show {output_file}[/cyan]")


if __name__ == "__main__":
    main()
