"""Roasting and praising functionality."""

import random
from rich.console import Console
from rich.panel import Panel
from roastbuddy.utils.git_utils import find_git_repo, get_last_commit, get_repo_path
from roastbuddy.utils.copilot_utils import (
    is_copilot_available,
    generate_roast_with_copilot,
    generate_praise_with_copilot,
    suggest_copilot_install
)
from roastbuddy.templates.roast_templates import ROAST_TEMPLATES, get_roast_category
from roastbuddy.templates.praise_templates import PRAISE_TEMPLATES, get_praise_category
from roastbuddy.core.config import get_config_value
from roastbuddy.core.database import add_interaction

console = Console()


def roast_code(last_commit: bool = True):
    """Generate a roast for the code."""
    repo = find_git_repo()
    
    if not repo:
        console.print("[red]❌ Not in a git repository![/red]")
        console.print("[yellow]Initialize git first: [bold]git init[/bold][/yellow]")
        return
    
    commit_data = get_last_commit(repo)
    
    if not commit_data:
        console.print("[yellow]⚠️ No commits found yet![/yellow]")
        console.print("[dim]Make your first commit and come back for a roast! 🔥[/dim]")
        return
    
    # Check if Copilot should be used
    use_copilot = get_config_value("use_copilot", "auto")
    copilot_available = is_copilot_available()
    
    roast_text = None
    source = "template"
    
    # Try Copilot if configured
    if use_copilot in ["auto", "always"] and copilot_available:
        roast_text = generate_roast_with_copilot(commit_data)
        source = "copilot"
        if roast_text:
            console.print("[dim]🤖 Roast powered by GitHub Copilot[/dim]\n")
    
    # Fallback to templates
    if not roast_text:
        if use_copilot == "always":
            console.print("[yellow]⚠️ Copilot not available but set to 'always'[/yellow]")
            suggest_copilot_install()
            return
        
        category = get_roast_category(commit_data)
        roast_text = random.choice(ROAST_TEMPLATES.get(category, ROAST_TEMPLATES["default"]))
        
        if not copilot_available and use_copilot == "auto":
            console.print("[dim]💡 Using built-in roasts (Copilot not available)[/dim]\n")
    
    # Display the roast
    console.print(Panel.fit(
        f"[bold red]🔥 Your Roast[/bold red]\n\n"
        f"{roast_text}\n\n"
        f"[dim]Commit: {commit_data['short_hash']} - {commit_data['message'][:50]}...[/dim]",
        title="Roast",
        border_style="red"
    ))
    
    # Save to database
    add_interaction("roast", roast_text, commit_data["hash"], source, commit_data["repo_path"])


def praise_code(last_commit: bool = True):
    """Generate praise for the code."""
    repo = find_git_repo()
    
    if not repo:
        console.print("[red]❌ Not in a git repository![/red]")
        console.print("[yellow]Initialize git first: [bold]git init[/bold][/yellow]")
        return
    
    commit_data = get_last_commit(repo)
    
    if not commit_data:
        console.print("[yellow]⚠️ No commits found yet![/yellow]")
        console.print("[dim]Make your first commit and come back for praise! ✨[/dim]")
        return
    
    # Check if Copilot should be used
    use_copilot = get_config_value("use_copilot", "auto")
    copilot_available = is_copilot_available()
    
    praise_text = None
    source = "template"
    
    # Try Copilot if configured
    if use_copilot in ["auto", "always"] and copilot_available:
        praise_text = generate_praise_with_copilot(commit_data)
        source = "copilot"
        if praise_text:
            console.print("[dim]🤖 Praise powered by GitHub Copilot[/dim]\n")
    
    # Fallback to templates
    if not praise_text:
        if use_copilot == "always":
            console.print("[yellow]⚠️ Copilot not available but set to 'always'[/yellow]")
            suggest_copilot_install()
            return
        
        category = get_praise_category(commit_data)
        praise_text = random.choice(PRAISE_TEMPLATES.get(category, PRAISE_TEMPLATES["default"]))
        
        if not copilot_available and use_copilot == "auto":
            console.print("[dim]💡 Using built-in praise (Copilot not available)[/dim]\n")
    
    # Display the praise
    console.print(Panel.fit(
        f"[bold green]✨ Your Praise[/bold green]\n\n"
        f"{praise_text}\n\n"
        f"[dim]Commit: {commit_data['short_hash']} - {commit_data['message'][:50]}...[/dim]",
        title="Praise",
        border_style="green"
    ))
    
    # Save to database
    add_interaction("praise", praise_text, commit_data["hash"], source, commit_data["repo_path"])
