"""Intelligent intake wizard for NIKAME.

3-layer confirmation flow:
1. Domain Mapping (Entities/Relationships)
2. Feature Selection (Infrastructure)
3. Infrastructure Tuning (Credentials/Scale)
"""

from __future__ import annotations
import click
import questionary
from typing import Any

from nikame.config.schema import NikameConfig
from nikame.cli.commands.domain import DomainUnderstandingEngine

class NikameWizard:
    """Manages the interactive project setup wizard."""

    def __init__(self):
        self.engine = DomainUnderstandingEngine()

    def run(self) -> NikameConfig:
        """Execute the full wizard flow."""
        click.clear()
        click.secho("🚀 NIKAME V2: Intelligent Project Setup", fg="cyan", bold=True)
        click.echo("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")

        # Layer 0: One-liner description
        description = questionary.text(
            "What are you building today?",
            placeholder="e.g., A RAG platform for legal document search with sub-second latency",
        ).ask()

        if not description:
             click.secho("Description required. Exiting.", fg="red")
             raise click.Abort()

        # Run Domain Engine
        with click.progressbar(length=100, label="Analyzing domain...") as bar:
            config = self.engine.analyze(description)
            bar.update(100)

        # Layer 1: Domain Mapping (Entities)
        config = self._layer_domain_mapping(config)

        # Layer 2: Feature Selection (Infra)
        config = self._layer_feature_selection(config)

        # Layer 3: Infra Tuning (Credentials handled by CredentialVault later)
        config = self._layer_infra_tuning(config)

        return config

    def _layer_domain_mapping(self, config: NikameConfig) -> NikameConfig:
        """Confirm and refine extracted entities."""
        click.secho("\nLayer 1: Domain Entities", fg="yellow", bold=True)
        
        entities = list(config.models.keys())
        if not entities:
            entities = ["User"] # Default
            
        confirmed_entities = questionary.checkbox(
            "I detected these core entities. Select the ones you want to keep:",
            choices=[questionary.Choice(e, checked=True) for e in entities],
        ).ask()

        if confirmed_entities is None:
             raise click.Abort()

        # Remove unselected
        for e in list(config.models.keys()):
            if e not in confirmed_entities:
                del config.models[e]

        # Add new ones
        new_entity = True
        while new_entity:
            name = questionary.text("Add another entity (leave blank to continue):").ask()
            if not name:
                new_entity = False
            else:
                from nikame.config.schema import DataModelConfig, FieldConfig
                config.models[name] = DataModelConfig(
                    fields={
                        "id": FieldConfig(type="int", required=True, unique=True),
                        "name": FieldConfig(type="str", required=True)
                    }
                )
        
        return config

    def _layer_feature_selection(self, config: NikameConfig) -> NikameConfig:
        """Confirm infrastructure components."""
        click.secho("\nLayer 2: Infrastructure Selection", fg="yellow", bold=True)
        
        choices = [
            questionary.Choice("PostgreSQL (Database)", value="postgres", checked=config.databases is not None and config.databases.postgres is not None),
            questionary.Choice("Redis/Dragonfly (Cache)", value="cache", checked=config.cache is not None),
            questionary.Choice("Redpanda/Kafka (Streaming)", value="messaging", checked=config.messaging is not None),
            questionary.Choice("MinIO/S3 (Storage)", value="storage", checked=config.storage is not None),
            questionary.Choice("Qdrant (Vector DB)", value="qdrant", checked=config.databases is not None and config.databases.qdrant is not None),
            questionary.Choice("Authentication (Keycloak/Postgres)", value="auth", checked=config.auth is not None),
        ]

        selected = questionary.checkbox(
            "Verify your infrastructure stack:",
            choices=choices
        ).ask()

        if selected is None:
            raise click.Abort()

        # Update config based on selection (Simplified for now)
        from nikame.config.schema import DatabasesConfig, CacheConfig, MessagingConfig, StorageConfig, AuthConfig
        
        if "postgres" not in selected: config.databases.postgres = None if config.databases else None
        if "cache" not in selected: config.cache = None
        if "messaging" not in selected: config.messaging = None
        if "storage" not in selected: config.storage = None
        if "qdrant" not in selected and config.databases: config.databases.qdrant = None
        if "auth" not in selected: config.auth = None

        return config

    def _layer_infra_tuning(self, config: NikameConfig) -> NikameConfig:
        """High-level tuning."""
        click.secho("\nLayer 3: Infrastructure Tuning", fg="yellow", bold=True)
        
        env = questionary.select(
            "Primary deployment target:",
            choices=["local", "kubernetes", "aws", "gcp"],
            default=config.environment.target
        ).ask()
        
        if env:
            config.environment.target = env

        scale = questionary.select(
            "Expected scale:",
            choices=["small", "medium", "large"],
            default=config.project.scale
        ).ask()
        
        if scale:
            config.project.scale = scale

        return config
