"""Context Engineering for the AI Copilot.

Builds RAG contexts and system prompts for local Ollama models so they
understand the exact schema and constraints of the NIKAME framework.
"""

import json
from typing import Any

from nikame.config.schema import NikameConfig


class ContextEngine:
    """Manages the context windows and prompts for AI generation."""

    def __init__(self) -> None:
        pass

    @staticmethod
    def _get_config_schema() -> dict[str, Any]:
        """Dynamically extract the valid JSON schema for NikameConfig."""
        # Using pydantic's schema generation
        if hasattr(NikameConfig, "model_json_schema"):
            return NikameConfig.model_json_schema() # type: ignore
        # Fallback for older pydantic
        return NikameConfig.schema() # type: ignore

    def build_blueprint_prompt(self) -> str:
        """System prompt specifically tailored for parsing user natural language into NikameConfig."""
        schema = json.dumps(self._get_config_schema(), indent=2)
        
        return (
            "You are NIKAME Copilot, a senior cloud architect and expert Python developer. "
            "Your job is to translate a user's natural language request into a highly optimized, "
            "production-ready backend infrastructure architecture.\n\n"
            "You MUST output EXACTLY one valid JSON object and absolutely nothing else. "
            "No markdown wrapping, no explanations, no chatter. Strictly JSON.\n\n"
            "The JSON you output MUST strictly conform to this JSON schema:\n"
            f"{schema}\n\n"
            "MANDATORY EXAMPLES OF GOOD CHOICES:\n"
            "- If they ask for 'AI', 'Semantic Search', or 'RAG', activate features=['rag-pipeline'] "
            "and add 'qdrant' to databases and vector_dbs.\n"
            "- If they ask for 'User Login' or 'SSO', add 'keycloak' or 'auth' to features.\n"
            "- If they ask for 'Subscriptions' or 'Payments', add 'stripe' to features.\n"
        )
        
    def build_fastapi_router_prompt(self, feature_name: str) -> str:
        """System prompt for synthesizing custom FastAPI business logic."""
        return (
            f"You are NIKAME Copilot, an expert backend engineer. "
            f"Write a fully functional FastAPI router for the feature: '{feature_name}'.\n\n"
            "RULES:\n"
            "1. Output ONLY beautifully formatted, production-ready Python code. No markdown or markdown ticks (```python).\n"
            "2. Ensure you import APIRouter from fastapi.\n"
            "3. Create an instance called `router = APIRouter(...)`.\n"
            "4. Add thorough exception handling and docstrings.\n"
            "5. If a database is needed, assume SQLAlchemy session injections via Depends().\n"
            "Do NOT include conversational text. Return only the raw Python script."
        )

    def build_sqlalchemy_prompt(self, feature_name: str) -> str:
        """System prompt for synthesizing SQLAlchemy models."""
        return (
            f"You are NIKAME Copilot, an expert database architect. "
            f"Write a comprehensive SQLAlchemy 2.0 declarative model for: '{feature_name}'.\n\n"
            "RULES:\n"
            "1. Output ONLY beautifully formatted, production-ready Python code. No markdown or markdown ticks.\n"
            "2. Inherit from a `Base` declarative class.\n"
            "3. Use `Mapped` and `mapped_column` type hinting (SQLAlchemy 2.0 style).\n"
            "4. Include UUID primary keys, created_at, updated_at timestamps.\n"
            "Do NOT include conversational text. Return only the raw Python script."
        )
