"""Initializer for RoastBuddy."""

import os
from pathlib import Path
from git import Repo, InvalidGitRepositoryError
from rich.console import Console
from roastbuddy.core.config import get_config_dir, save_config, DEFAULT_CONFIG
from roastbuddy.core.database import initialize_database

console = Console()


def is_git_repository(path: str) -> bool:
    """Check if the path is a git repository."""
    try:
        Repo(path, search_parent_directories=True)
        return True
    except InvalidGitRepositoryError:
        return False


def initialize_roastbuddy(path: str = ".") -> bool:
    """Initialize RoastBuddy in a git repository."""
    path = Path(path).resolve()
    
    # Check if it's a git repository
    if not is_git_repository(str(path)):
        console.print(f"[red]❌ {path} is not a git repository![/red]")
        console.print("[yellow]💡 Initialize git first: [bold]git init[/bold][/yellow]")
        return False
    
    try:
        # Create config directory
        config_dir = get_config_dir()
        console.print(f"[dim]Creating config directory: {config_dir}[/dim]")
        
        # Initialize database
        console.print("[dim]Initializing database...[/dim]")
        initialize_database()
        
        # Save default configuration
        console.print("[dim]Creating default configuration...[/dim]")
        save_config(DEFAULT_CONFIG)
        
        # Create .roastbuddy marker in repo
        marker_file = path / ".roastbuddy"
        if not marker_file.exists():
            marker_file.touch()
            console.print(f"[dim]Created repository marker: {marker_file}[/dim]")
        
        console.print("\n[bold green]🎉 RoastBuddy initialized successfully![/bold green]")
        console.print("\n[cyan]Next steps:[/cyan]")
        console.print("  • [bold]roastbuddy roast[/bold] - Get roasted!")
        console.print("  • [bold]roastbuddy praise[/bold] - Get some praise")
        console.print("  • [bold]roastbuddy status[/bold] - Check your stats")
        
        return True
        
    except Exception as e:
        console.print(f"[red]❌ Error during initialization: {e}[/red]")
        return False
