"""planfile commands for proxym CLI."""

import subprocess
import click

from proxym.cli._client import print_json_if_yaml


@click.group("planfile")
def planfile_group():
    """Manage planfile strategies."""
    pass


@planfile_group.command("import")
@click.argument("strategy_path")
@click.option("--project", "-p", required=True, help="Project name to import tickets into")
@click.option("--dry-run", is_flag=True, help="Show what would be imported without creating tickets")
@click.pass_context
def import_strategy(ctx, strategy_path, project, dry_run):
    """Import strategy.yaml as proxym tickets."""
    from proxym.planfile.importer import import_strategy
    
    try:
        result = import_strategy(strategy_path, project, dry_run=dry_run)
        
        if print_json_if_yaml(ctx.obj, result):
            return
            
        click.echo(f"\n✓ Imported strategy from {strategy_path}")
        click.echo(f"  Project: {project}")
        click.echo(f"  Tickets created: {result['tickets_created']}")
        click.echo(f"  Sprints: {len(result['sprints'])}")
        
        for sprint in result["sprints"]:
            click.echo(f"    - {sprint['name']}: {len(sprint['tickets'])} tickets")
            
        if dry_run:
            click.echo("\n  (Dry run - no tickets were actually created)")
            
    except Exception as e:
        click.echo(f"✗ Failed to import strategy: {e}", err=True)
        raise click.ClickException(str(e))


@planfile_group.command("execute")
@click.argument("strategy_path")
@click.option("--project-path", "-d", default=".", help="Project directory path")
@click.option("--sprint", "-s", help="Execute only specific sprint")
def execute_strategy(strategy_path, project_path, sprint):
    """Execute strategy via llx (delegates to `llx plan apply`)."""
    cmd = ["llx", "plan", "apply", strategy_path, project_path]
    if sprint:
        cmd.extend(["--sprint", sprint])
    
    click.echo(f"Executing: {' '.join(cmd)}")
    
    try:
        result = subprocess.run(cmd, check=True)
        click.echo("✓ Strategy execution completed")
    except subprocess.CalledProcessError as e:
        click.echo(f"✗ Strategy execution failed: {e}", err=True)
        raise click.ClickException(str(e))
    except FileNotFoundError:
        click.echo("✗ llx command not found. Is llx installed and in PATH?", err=True)
        raise click.ClickException("llx not found")


@planfile_group.command("gates")
@click.argument("strategy_path")
@click.option("--project-path", "-d", default=".", help="Project directory path")
@click.pass_context
def check_gates(ctx, strategy_path, project_path):
    """Check quality gates from strategy."""
    from proxym.planfile.tracker import check_quality_gates
    
    try:
        results = check_quality_gates(strategy_path, project_path)
        
        if print_json_if_yaml(ctx.obj, {"quality_gates": results}):
            return
            
        click.echo(f"\nQuality Gates for {strategy_path}")
        click.echo("=" * 50)
        
        passed = sum(1 for r in results if r["passed"])
        total = len(results)
        
        for gate in results:
            icon = "✓" if gate["passed"] else "✗"
            actual = gate["actual"] if gate["actual"] is not None else "N/A"
            click.echo(f"  {icon} {gate['name']}: {actual} {gate['operator']} {gate['threshold']}")
            if gate.get("description"):
                click.echo(f"    {gate['description']}")
                
        click.echo(f"\nSummary: {passed}/{total} gates passed")
        
    except Exception as e:
        click.echo(f"✗ Failed to check quality gates: {e}", err=True)
        raise click.ClickException(str(e))


@planfile_group.command("status")
@click.argument("project_name")
@click.pass_context
def strategy_status(ctx, project_name):
    """Show execution status of imported strategy for a project."""
    from proxym.planfile.tracker import get_strategy_progress
    
    try:
        status = get_strategy_progress(project_name)
        
        if print_json_if_yaml(ctx.obj, status):
            return
            
        click.echo(f"\nStrategy Status for {project_name}")
        click.echo("=" * 40)
        click.echo(f"  Total tasks: {status['total_tasks']}")
        click.echo(f"  Completed: {status['completed']}")
        click.echo(f"  In progress: {status['in_progress']}")
        click.echo(f"  Remaining: {status['remaining']}")
        click.echo(f"  Progress: {status['progress_pct']}%")
        
    except Exception as e:
        click.echo(f"✗ Failed to get strategy status: {e}", err=True)
        raise click.ClickException(str(e))
