"""Main CLI entry point."""

import json
from pathlib import Path
from typing import Optional

import typer
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.table import Table

from .processor import MediaProcessor
from .report import ReportGenerator
from .watermark import WatermarkEngine

app = typer.Typer(
    name="synth-comply",
    help="Batch compliance processing for AI-generated media",
    add_completion=False,
)
console = Console()


@app.command()
def process(
    input_dir: Path = typer.Argument(..., help="Directory containing media files to process"),
    output_dir: Path = typer.Argument(..., help="Directory for watermarked output files"),
    watermark_text: str = typer.Option(
        "AI-GENERATED", "--text", "-t", help="Watermark text to embed"
    ),
    watermark_opacity: float = typer.Option(
        0.3, "--opacity", "-o", min=0.0, max=1.0, help="Watermark opacity (0.0-1.0)"
    ),
    invisible: bool = typer.Option(
        False, "--invisible", "-i", help="Add invisible forensic watermark"
    ),
    sign: bool = typer.Option(True, "--sign/--no-sign", help="Add C2PA-style digital signature"),
    metadata: Optional[str] = typer.Option(
        None, "--metadata", "-m", help="JSON string of metadata to embed"
    ),
    report: bool = typer.Option(True, "--report/--no-report", help="Generate compliance report"),
    formats: str = typer.Option(
        "jpg,png,mp4,mov,mp3,wav", "--formats", "-f", help="Comma-separated file extensions"
    ),
):
    """Process media files with watermarks and compliance metadata."""

    if not input_dir.exists():
        console.print(f"[red]Error: Input directory '{input_dir}' does not exist[/red]")
        raise typer.Exit(1)

    output_dir.mkdir(parents=True, exist_ok=True)

    # Parse metadata
    metadata_dict = {}
    if metadata:
        try:
            metadata_dict = json.loads(metadata)
        except json.JSONDecodeError:
            console.print(f"[red]Error: Invalid JSON metadata: {metadata}[/red]")
            raise typer.Exit(1)

    # Initialize processors
    watermark_engine = WatermarkEngine(
        text=watermark_text, opacity=watermark_opacity, invisible=invisible
    )
    processor = MediaProcessor(watermark_engine=watermark_engine, sign=sign)

    # Find files
    allowed_formats = {f".{fmt.strip().lower()}" for fmt in formats.split(",")}
    files = [f for f in input_dir.rglob("*") if f.suffix.lower() in allowed_formats]

    if not files:
        console.print(f"[yellow]No files found with formats: {formats}[/yellow]")
        raise typer.Exit(0)

    console.print(f"[cyan]Found {len(files)} files to process[/cyan]\n")

    # Process files
    results = []
    with Progress(
        SpinnerColumn(),
        TextColumn("[progress.description]{task.description}"),
        console=console,
    ) as progress:
        task = progress.add_task("Processing files...", total=len(files))

        for file_path in files:
            try:
                output_path = output_dir / file_path.relative_to(input_dir)
                output_path.parent.mkdir(parents=True, exist_ok=True)

                result = processor.process_file(file_path, output_path, metadata_dict)
                results.append(result)

                status = "[green]✓[/green]" if result["success"] else "[red]✗[/red]"
                console.print(f"{status} {file_path.name}")

            except Exception as e:
                console.print(f"[red]✗ {file_path.name}: {str(e)}[/red]")
                results.append(
                    {
                        "file": str(file_path),
                        "success": False,
                        "error": str(e),
                        "timestamp": None,
                    }
                )

            progress.advance(task)

    # Summary
    success_count = sum(1 for r in results if r["success"])
    console.print(f"\n[bold]Processed {success_count}/{len(files)} files successfully[/bold]")

    # Generate report
    if report:
        report_path = output_dir / "compliance_report.html"
        report_generator = ReportGenerator()
        report_generator.generate(
            results=results,
            output_path=report_path,
            config={
                "watermark_text": watermark_text,
                "watermark_opacity": watermark_opacity,
                "invisible": invisible,
                "sign": sign,
                "metadata": metadata_dict,
            },
        )
        console.print(f"\n[cyan]📄 Compliance report saved to: {report_path}[/cyan]")


@app.command()
def verify(
    file_path: Path = typer.Argument(..., help="File to verify"),
):
    """Verify watermark and signature on a processed file."""

    if not file_path.exists():
        console.print(f"[red]Error: File '{file_path}' does not exist[/red]")
        raise typer.Exit(1)

    processor = MediaProcessor(watermark_engine=None, sign=True)
    verification = processor.verify_file(file_path)

    table = Table(title=f"Verification: {file_path.name}")
    table.add_column("Check", style="cyan")
    table.add_column("Status", style="bold")
    table.add_column("Details")

    for check, result in verification.items():
        status = "[green]✓ PASS[/green]" if result.get("valid") else "[red]✗ FAIL[/red]"
        details = result.get("details", "N/A")
        table.add_row(check.replace("_", " ").title(), status, str(details))

    console.print(table)


@app.command()
def config(
    init: bool = typer.Option(False, "--init", help="Initialize default config file"),
):
    """Manage configuration."""

    config_path = Path.home() / ".synth-comply.toml"

    if init:
        default_config = """
# Synth Media Compliance CLI Configuration

[watermark]
text = "AI-GENERATED"
opacity = 0.3
position = "bottom-right"  # top-left, top-right, bottom-left, bottom-right, center
font_size = 24

[signature]
enabled = true
algorithm = "RSA-SHA256"

[metadata]
# Default metadata to embed in all files
generator = "synth-media-compliance-cli"
standard = "EU-AI-ACT-2026"

[output]
preserve_structure = true
suffix = "_compliant"
"""
        config_path.write_text(default_config.strip())
        console.print(f"[green]✓ Config file created at: {config_path}[/green]")
    else:
        if config_path.exists():
            console.print(f"[cyan]Config location: {config_path}[/cyan]\n")
            console.print(config_path.read_text())
        else:
            console.print(f"[yellow]No config file found. Run 'synth-comply config --init'[/yellow]")


if __name__ == "__main__":
    app()
