"""nikame copilot — Intelligent natural language to backend generation.

Uses local Ollama models to parse a user's intent into a valid NikameConfig blueprint.
"""

from __future__ import annotations

import asyncio
from pathlib import Path
from typing import Any

import click
import questionary
from rich.panel import Panel

from nikame.cli.commands.init import _generate_project
from nikame.codegen.ai_synthesizer import AISynthesizer
from nikame.codegen.context_engine import ContextEngine
from nikame.config.loader import load_config_from_dict
from nikame.exceptions import NikameError
from nikame.utils.logger import console


@click.command(name="copilot")
@click.argument("prompt", nargs=-1, required=True)
@click.option(
    "--output", "-o",
    type=click.Path(path_type=Path),
    default=Path("."),
    help="Output directory for generated files.",
)
@click.option(
    "--model", "-m",
    type=str,
    default="llama3",
    help="Local Ollama model to use for generation (e.g. llama3, codellama).",
)
@click.option(
    "--dry-run",
    is_flag=True,
    help="Preview generated files without writing.",
)
def copilot(prompt: tuple[str, ...], output: Path, model: str, dry_run: bool) -> None:
    """Build a backend from a natural language prompt.
    
    Example:
    nikame copilot "A scalable SaaS for law firms with Qdrant semantics and Stripe"
    """
    user_request = " ".join(prompt)
    console.print(f"\n[bold cyan]🚀 NIKAME Copilot initialized[/bold cyan]")
    console.print(f"[dim]Model: {model} (Local Ollama)[/dim]")
    console.print(f"[dim]Analyzing request: '{user_request}'[/dim]\n")
    
    synthesizer = AISynthesizer(model=model)
    context_engine = ContextEngine()
    
    try:
        # Check if Ollama is running and model is downloaded
        with console.status(f"[info]Connecting to local {model}...[/info]"):
            synthesizer.check_readiness()
    
        # Generate the blueprint
        with console.status("[info]AI is designing your architecture...[/info]"):
            system_prompt = context_engine.build_blueprint_prompt()
            config_dict = synthesizer.draft_config(system_prompt, user_request)
            
            # Use strict Pydantic parsing
            config = load_config_from_dict(config_dict)
            
        # Present the plan
        _present_plan(config_dict)
        
        # Confirm
        action = questionary.select(
            "Copilot has tailored this architecture. Proceed with generation?",
            choices=["Yes, build it", "Cancel"]
        ).ask()
        
        if action == "Cancel":
            console.print("[warning]Generation cancelled.[/warning]")
            raise SystemExit(0)
            
        # Generation step
        console.print("\n[bold green]Building Backend...[/bold green]")
        asyncio.run(_generate_project(config, output, dry_run=dry_run))
        
    except NikameError as e:
        console.print(f"\n[bold red]❌ Copilot Error:[/bold red] {e}")
        raise SystemExit(1)
    except Exception as e:
        console.print(f"\n[bold red]❌ Unexpected Error:[/bold red] {e}")
        raise SystemExit(1)


def _present_plan(config_dict: dict[str, Any]) -> None:
    """Render the AI's proposed architecture in a nice summary."""
    name = config_dict.get("name", "Unknown")
    env = config_dict.get("environment", {})
    features = config_dict.get("features", [])
    dbs = list(config_dict.get("databases", {}).keys())
    
    summary = (
        f"[bold white]Project Name:[/bold white] {name}\n"
        f"[bold white]Target Env:[/bold white] {env.get('target', 'local')} ({env.get('profile', 'local')})\n"
        f"[bold white]Databases:[/bold white] {', '.join(dbs) if dbs else 'None'}\n"
        f"[bold white]Features:[/bold white] {', '.join(features) if features else 'None'}\n"
    )
    
    mlops = config_dict.get("mlops")
    if mlops:
        vdbs = mlops.get("vector_dbs", [])
        models = mlops.get("serving", [])
        if vdbs or models:
            summary += f"[bold white]AI/ML:[/bold white] {', '.join(models + vdbs)}\n"
            
    console.print(Panel(summary, title="[bold green]🧠 AI Architectural Draft[/bold green]", border_style="green"))
