import shutil
import sys
from pathlib import Path
import typer
from rich.console import Console
from rich.panel import Panel

app = typer.Typer()
console = Console()

@app.command()
def main(force: bool = typer.Option(False, "--force", "-f", help="Overwrite existing files")):
    """
    Initialize GSD-Lite in the current directory.
    """
    # 1. Locate the bundled templates
    # We look for the 'template' folder relative to this script
    package_dir = Path(__file__).parent
    source_dir = package_dir / "template"
    
    # 2. Define destination
    cwd = Path.cwd()
    # The root folder for the protocol
    root_dir = cwd / "gsd-lite"
    # The specific home for the templates
    template_dest = root_dir / "template"

    console.print(Panel.fit("[bold cyan]GSD-Lite Scaffolder[/bold cyan]", border_style="cyan"))

    # 3. Validation
    if not source_dir.exists():
        console.print(f"[bold red]Error:[/bold red] Template directory not found at {source_dir}")
        console.print("This usually means the package was built incorrectly.")
        raise typer.Exit(code=1)

    if template_dest.exists() and not force:
        console.print(f"[yellow]Warning:[/yellow] Directory [bold]{template_dest}[/bold] already exists.")
        console.print("Use [bold]--force[/bold] to overwrite.")
        raise typer.Exit(code=1)

    # 4. Copying
    try:
        # Ensure root exists
        root_dir.mkdir(exist_ok=True)

        if template_dest.exists() and force:
            shutil.rmtree(template_dest)
        
        shutil.copytree(source_dir, template_dest)
        
        # 5. Success
        console.print(f"[green]✔ Successfully initialized GSD-Lite templates in:[/green] {template_dest}")
        console.print("\n[bold]Next Steps:[/bold]")
        console.print("1. Tell your agent to load file [bold]gsd-lite/template/PROTOCOL.md[/bold]")
        console.print("2. Describe your task - your session is now powered by gsd!")
        
    except Exception as e:
        console.print(f"[bold red]Error copying files:[/bold red] {e}")
        raise typer.Exit(code=1)

if __name__ == "__main__":
    app()
