"""Command-line interface for PR Guardian."""

import sys
from pathlib import Path
from typing import Optional, List
import click
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from .scanner import CodeScanner
from .analyzer import AIConfidenceAnalyzer


console = Console()


@click.group()
@click.version_option(version="0.1.0")
def main() -> None:
    """PR Guardian - Lightweight AI code validation for GitHub PRs."""
    pass


@main.command()
@click.argument("paths", nargs=-1, type=click.Path(exists=True))
@click.option("--output", "-o", type=click.Choice(["table", "json", "markdown"]), default="table")
@click.option("--threshold", "-t", type=float, default=0.7, help="AI confidence threshold for warnings")
def scan(paths: tuple, output: str, threshold: float) -> None:
    """Scan code files for AI-generated patterns."""
    if not paths:
        console.print("[red]Error: No paths provided[/red]")
        sys.exit(1)
    
    scanner = CodeScanner()
    analyzer = AIConfidenceAnalyzer()
    
    # Collect all files to scan
    files_to_scan: List[Path] = []
    for path_str in paths:
        path = Path(path_str)
        if path.is_file():
            files_to_scan.append(path)
        elif path.is_dir():
            # Scan Python, JS, TS files
            files_to_scan.extend(path.rglob("*.py"))
            files_to_scan.extend(path.rglob("*.js"))
            files_to_scan.extend(path.rglob("*.ts"))
            files_to_scan.extend(path.rglob("*.jsx"))
            files_to_scan.extend(path.rglob("*.tsx"))
    
    if not files_to_scan:
        console.print("[yellow]No files found to scan[/yellow]")
        sys.exit(0)
    
    console.print(f"[cyan]Scanning {len(files_to_scan)} files...[/cyan]\n")
    
    # Scan files
    results = []
    with console.status("[bold green]Scanning...") as status:
        for file_path in files_to_scan:
            status.update(f"[bold green]Scanning {file_path.name}...")
            result = scanner.scan_file(file_path)
            results.append(result)
    
    # Analyze results
    report = analyzer.analyze(results)
    
    # Output results
    if output == "table":
        _display_table(report, results, threshold)
    elif output == "markdown":
        md = analyzer.format_markdown(report, results)
        console.print(md)
    elif output == "json":
        import json
        data = {
            "overall_risk": report.overall_risk,
            "avg_ai_confidence": report.avg_ai_confidence,
            "total_issues": report.total_issues,
            "files": [
                {
                    "path": r.file_path,
                    "ai_confidence": r.ai_confidence_score,
                    "issues": len(r.issues),
                    "errors": r.error_count,
                }
                for r in results
            ]
        }
        console.print(json.dumps(data, indent=2))


def _display_table(report, results, threshold):
    """Display results as a rich table."""
    # Summary panel
    risk_color = {"low": "green", "medium": "yellow", "high": "red"}[report.overall_risk]
    summary = f"""[bold]Files Scanned:[/bold] {report.scanned_files}
[bold]Average AI Confidence:[/bold] {report.avg_ai_confidence:.0%}
[bold]Total Issues:[/bold] {report.total_issues}
[bold]Overall Risk:[/bold] [{risk_color}]{report.overall_risk.upper()}[/{risk_color}]"""
    
    console.print(Panel(summary, title="🛡️ PR Guardian Summary", border_style="blue"))
    console.print()
    
    # Files table
    table = Table(title="Scanned Files")
    table.add_column("File", style="cyan")
    table.add_column("AI Confidence", justify="right")
    table.add_column("Issues", justify="right")
    table.add_column("Status", justify="center")
    
    for result in sorted(results, key=lambda r: -r.ai_confidence_score):
        confidence = result.ai_confidence_score
        
        # Status emoji
        if confidence > threshold:
            status = "🚨"
            confidence_style = "bold red"
        elif confidence > 0.4:
            status = "⚠️"
            confidence_style = "yellow"
        else:
            status = "✅"
            confidence_style = "green"
        
        file_name = Path(result.file_path).name
        table.add_row(
            file_name,
            f"[{confidence_style}]{confidence:.0%}[/{confidence_style}]",
            str(len(result.issues)),
            status
        )
    
    console.print(table)
    console.print()
    
    # High-risk files warning
    if report.high_risk_files:
        console.print(Panel(
            f"[yellow]Found {len(report.high_risk_files)} high-risk file(s) with AI confidence > {threshold:.0%}[/yellow]",
            title="⚠️ Warning",
            border_style="yellow"
        ))


@main.command()
@click.argument("pr_number", type=int)
@click.option("--repo", "-r", help="Repository in format owner/repo")
@click.option("--token", "-t", envvar="GITHUB_TOKEN", help="GitHub token")
def check_pr(pr_number: int, repo: Optional[str], token: Optional[str]) -> None:
    """Check a GitHub PR for AI-generated code."""
    if not repo:
        console.print("[red]Error: --repo is required[/red]")
        sys.exit(1)
    
    if not token:
        console.print("[red]Error: GITHUB_TOKEN not provided[/red]")
        sys.exit(1)
    
    from github import Github
    
    gh = Github(token)
    repository = gh.get_repo(repo)
    pr = repository.get_pull(pr_number)
    
    console.print(f"[cyan]Checking PR #{pr_number}: {pr.title}[/cyan]\n")
    
    # Get changed files
    files = pr.get_files()
    
    # Scan each file
    scanner = CodeScanner()
    results = []
    
    for file in files:
        if file.filename.endswith(('.py', '.js', '.ts', '.jsx', '.tsx')):
            console.print(f"Scanning {file.filename}...")
            
            # Download file content
            content = repository.get_contents(file.filename, ref=pr.head.sha)
            
            # Write to temp file and scan
            temp_path = Path(f"/tmp/{Path(file.filename).name}")
            temp_path.write_bytes(content.decoded_content)
            
            result = scanner.scan_file(temp_path)
            results.append(result)
            temp_path.unlink()
    
    # Generate report
    analyzer = AIConfidenceAnalyzer()
    report = analyzer.analyze(results)
    
    # Post as comment
    comment_body = analyzer.format_markdown(report, results)
    pr.create_issue_comment(comment_body)
    
    console.print(f"\n[green]✓ Posted scan results to PR #{pr_number}[/green]")


if __name__ == "__main__":
    main()
