"""CLI for aicert-pro baseline regression enforcement."""

import json
import subprocess
import sys
from pathlib import Path
from typing import Optional

import typer

from .baseline import (
    baseline_path,
    check_from_run,
    load_baseline,
    save_from_run,
)
from .license import LicenseError, require_pro

app = typer.Typer(
    name="aicert-pro",
    help="Pro baseline regression enforcement for aicert CLI.",
    add_completion=False,
)


def run_aicert(config_path: Path) -> Path:
    """Run aicert stability evaluation and return the run directory.
    
    Args:
        config_path: Path to aicert.yaml configuration file.
        
    Returns:
        Path to the run directory containing summary.json.
        
    Exits:
        With the same exit code if aicert fails.
    """
    cmd = [sys.executable, "-m", "aicert", "stability", str(config_path), "--ci"]
    result = subprocess.run(cmd, capture_output=True, text=True)
    
    if result.returncode != 0:
        typer.echo(f"aicert failed:\n{result.stderr}", err=True)
        raise typer.Exit(result.returncode)
    
    # Try to extract run directory from stdout
    # aicert outputs something like "Run complete. Results in: /path/to/run/dir"
    for line in result.stdout.strip().split("\n"):
        if "Run complete" in line or "Results in" in line:
            # Extract path from line
            parts = line.split()
            for part in parts:
                if part.startswith("/") or (len(part) > 1 and part[1] == ":"):
                    run_dir = Path(part)
                    if run_dir.exists():
                        return run_dir
    
    # Fallback: assume default artifact location
    # Default is typically ~/.aicert/runs/<timestamp>
    from datetime import datetime
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    run_dir = Path.home() / ".aicert" / "runs" / timestamp
    
    if not run_dir.exists():
        raise typer.BadParameter(f"Could not determine run directory from aicert output. "
                                  f"Please specify run directory directly.")
    
    return run_dir


@app.command("license")
def license_verify() -> None:
    """Verify pro license."""
    require_pro()
    typer.echo("License is valid.")


baseline_app = typer.Typer(help="Manage baselines for regression enforcement.")
app.add_typer(baseline_app, name="baseline")


@baseline_app.command("save")
def baseline_save(
    path: Path = typer.Argument(
        ...,
        help="Path to run directory or .yaml config file",
    ),
    baseline_dir: Path | None = typer.Option(
        None,
        "--baseline-dir",
        "-b",
        help="Directory to store baselines",
    ),
) -> None:
    """Save baseline metrics from a run directory or run aicert first."""
    try:
        require_pro()
    except LicenseError:
        raise typer.Exit(5)
    
    # Determine if path is a config file or run directory
    if path.suffix == ".yaml" or path.suffix == ".yml":
        # Run aicert first
        run_dir = run_aicert(path)
        typer.echo(f"Evaluation complete. Run directory: {run_dir}")
    else:
        run_dir = path
    
    data = save_from_run(run_dir, baseline_dir)
    result_path = baseline_path(data["project"], baseline_dir)
    typer.echo(f"Baseline saved to {result_path}")


@baseline_app.command("check")
def baseline_check(
    path: Path = typer.Argument(
        ...,
        help="Path to run directory or .yaml config file",
    ),
    baseline_dir: Path | None = typer.Option(
        None,
        "--baseline-dir",
        "-b",
        help="Directory to store baselines",
    ),
) -> None:
    """Check current run against baseline for regressions."""
    try:
        require_pro()
    except LicenseError:
        raise typer.Exit(5)
    
    # Determine if path is a config file or run directory
    if path.suffix == ".yaml" or path.suffix == ".yml":
        # Run aicert first
        run_dir = run_aicert(path)
        typer.echo(f"Evaluation complete. Run directory: {run_dir}")
    else:
        run_dir = path
    
    passed = check_from_run(run_dir, baseline_dir)
    if not passed:
        raise typer.Exit(2)
    typer.echo("Baseline check passed.")


@baseline_app.command("show")
def baseline_show(
    project: str = typer.Argument(..., help="Project name"),
    baseline_dir: Path | None = typer.Option(
        None,
        "--baseline-dir",
        "-b",
        help="Directory to store baselines",
    ),
) -> None:
    """Show baseline metrics for a project."""
    require_pro()
    path = baseline_path(project, baseline_dir)
    if not path.exists():
        raise typer.BadParameter(f"Baseline not found for project '{project}'")
    data = load_baseline(path)
    typer.echo(json.dumps(data, indent=2))


def main() -> None:
    """Entry point for aicert-pro CLI."""
    app()


if __name__ == "__main__":
    app()
