"""Copilot CLI detection and integration."""

import subprocess
from typing import Optional, Dict, Any
from rich.console import Console

console = Console()


def is_copilot_available() -> bool:
    """Check if GitHub Copilot CLI is available."""
    try:
        result = subprocess.run(
            ["gh", "copilot", "--version"],
            capture_output=True,
            text=True,
            timeout=5
        )
        return result.returncode == 0
    except (subprocess.TimeoutExpired, FileNotFoundError, Exception):
        return False


def get_copilot_suggestion(prompt: str, system_prompt: Optional[str] = None) -> Optional[str]:
    """Get a suggestion from GitHub Copilot CLI."""
    if not is_copilot_available():
        return None
    
    try:
        # Build the command
        cmd = ["gh", "copilot", "suggest", "-t", "shell"]
        
        full_prompt = prompt
        if system_prompt:
            full_prompt = f"{system_prompt}\n\n{prompt}"
        
        # Run the command
        result = subprocess.run(
            cmd + [full_prompt],
            capture_output=True,
            text=True,
            timeout=30
        )
        
        if result.returncode == 0:
            return result.stdout.strip()
        else:
            return None
            
    except Exception as e:
        console.print(f"[yellow]Copilot CLI error: {e}[/yellow]")
        return None


def generate_roast_with_copilot(commit_data: Dict[str, Any]) -> Optional[str]:
    """Generate a roast using Copilot CLI."""
    if not is_copilot_available():
        return None
    
    system_prompt = """You are RoastBuddy, a witty but supportive coding companion. 
Your job is to roast code commits in a humorous way that's funny but never mean-spirited.
Keep roasts short (2-3 sentences), use emojis, and end with a constructive tip.
Be playful, sarcastic, but ultimately encouraging."""
    
    commit_info = (
        f"Commit: {commit_data.get('message', 'No message')}\n"
        f"Files changed: {commit_data.get('files_changed', 0)}\n"
        f"Lines: +{commit_data.get('lines_added', 0)} -{commit_data.get('lines_deleted', 0)}\n"
        f"Clean message: {commit_data.get('is_clean', False)}"
    )
    
    prompt = f"Generate a witty roast for this commit:\n{commit_info}"
    
    return get_copilot_suggestion(prompt, system_prompt)


def generate_praise_with_copilot(commit_data: Dict[str, Any]) -> Optional[str]:
    """Generate praise using Copilot CLI."""
    if not is_copilot_available():
        return None
    
    system_prompt = """You are RoastBuddy, a supportive coding companion.
Your job is to genuinely praise good work and celebrate achievements.
Keep praise short (2-3 sentences), use emojis, and be enthusiastic and specific.
Be genuine and encouraging."""
    
    commit_info = (
        f"Commit: {commit_data.get('message', 'No message')}\n"
        f"Files changed: {commit_data.get('files_changed', 0)}\n"
        f"Lines: +{commit_data.get('lines_added', 0)} -{commit_data.get('lines_deleted', 0)}\n"
        f"Clean message: {commit_data.get('is_clean', False)}"
    )
    
    prompt = f"Generate enthusiastic praise for this commit:\n{commit_info}"
    
    return get_copilot_suggestion(prompt, system_prompt)


def suggest_copilot_install():
    """Suggest installing GitHub Copilot CLI."""
    console.print("\n[bold cyan]💡 GitHub Copilot CLI not found[/bold cyan]")
    console.print("\n[yellow]RoastBuddy works best with GitHub Copilot CLI for dynamic roasts![/yellow]")
    console.print("\n[dim]To install:[/dim]")
    console.print("  1. Install GitHub CLI: [bold]https://cli.github.com/[/bold]")
    console.print("  2. Install Copilot extension: [bold]gh extension install github/gh-copilot[/bold]")
    console.print("\n[dim]Don't worry! RoastBuddy will use built-in templates for now.[/dim]\n")
