"""
MLL Intake Configuration Module
Centralized configuration management with environment variable support
"""

import os
from pathlib import Path
from typing import Optional, Dict, Any, List
from pydantic import BaseModel, Field

# Load environment variables
try:
    from dotenv import load_dotenv
    load_dotenv()
except ImportError:
    pass

# Project root directory
PROJECT_ROOT = Path(__file__).parent.absolute()


class ModelConfig(BaseModel):
    """LLM Model Configuration"""
    api_key: str = Field(default_factory=lambda: os.getenv("ANTHROPIC_API_KEY", ""))
    model_name: str = Field(default_factory=lambda: os.getenv("ANTHROPIC_MODEL", "claude-sonnet-4-20250514"))
    max_tokens: int = Field(default_factory=lambda: int(os.getenv("MAX_TOKENS", "4096")))
    temperature: float = Field(default_factory=lambda: float(os.getenv("TEMPERATURE", "0.1")))


class DataConfig(BaseModel):
    """Data Paths Configuration"""
    iris_path: Path = Field(default_factory=lambda: PROJECT_ROOT / os.getenv("IRIS_DATA_PATH", "data/IRIS_Solution_Intake_requests.xlsx"))
    epics_path: Path = Field(default_factory=lambda: PROJECT_ROOT / os.getenv("JIRA_EPICS_PATH", "data/MLL_JIRA_Epics_extract.xlsx"))
    stories_path: Path = Field(default_factory=lambda: PROJECT_ROOT / os.getenv("JIRA_STORIES_PATH", "data/MLL_JIRA_Userstory_extracts.xlsx"))


class VectorConfig(BaseModel):
    """Vector Store Configuration"""
    embedding_model: str = Field(default_factory=lambda: os.getenv("EMBEDDING_MODEL", "all-MiniLM-L6-v2"))
    index_path: Path = Field(default_factory=lambda: PROJECT_ROOT / os.getenv("VECTOR_INDEX_PATH", "data/vector_index.faiss"))
    top_k: int = Field(default_factory=lambda: int(os.getenv("TOP_K_RESULTS", "5")))
    similarity_threshold: float = Field(default_factory=lambda: float(os.getenv("SIMILARITY_THRESHOLD", "0.7")))


class AppConfig(BaseModel):
    """Application Configuration"""
    app_name: str = Field(default_factory=lambda: os.getenv("APP_NAME", "MLL Intake Assistant"))
    debug: bool = Field(default_factory=lambda: os.getenv("DEBUG", "false").lower() == "true")
    log_level: str = Field(default_factory=lambda: os.getenv("LOG_LEVEL", "INFO"))


class Settings(BaseModel):
    """Main Settings Container"""
    model: ModelConfig = Field(default_factory=ModelConfig)
    data: DataConfig = Field(default_factory=DataConfig)
    vector: VectorConfig = Field(default_factory=VectorConfig)
    app: AppConfig = Field(default_factory=AppConfig)
    
    def validate_api_key(self) -> bool:
        """Validate that API key is present"""
        return bool(self.model.api_key and self.model.api_key != "your_api_key_here")


# Global settings instance
settings = Settings()


# MLL Domain Constants
MLL_SITES = {
    "6749": {"name": "JUAREZ", "country": "MX", "region": "Americas"},
    "6750": {"name": "JACKSONVILLE", "country": "US", "region": "Americas"},
    "6751": {"name": "LIMERICK", "country": "IE", "region": "EMEA"},
    "6752": {"name": "GURABO", "country": "PR", "region": "Americas"},
    "6753": {"name": "LEEDS", "country": "GB", "region": "EMEA"},
    "6754": {"name": "ATHENS", "country": "US", "region": "Americas"},
    "6755": {"name": "CORK", "country": "IE", "region": "EMEA"},
    "6756": {"name": "SCHAFFHAUSEN", "country": "CH", "region": "EMEA"},
}

CAPABILITY_CENTERS = {
    "agile_demand": {
        "name": "Agile Demand",
        "requires_nexus": True,
        "description": "End-to-end simple industrialized services, non-project/small scope"
    },
    "approved_project": {
        "name": "Approved Project Demand",
        "requires_nexus": True,
        "description": "Part of larger portfolio project with valid Nexus ID"
    },
    "estimate_demand": {
        "name": "Request for Estimate",
        "requires_nexus": False,
        "description": "Request for BP estimate for following year (65%)"
    },
    "ts_internal": {
        "name": "TS Internal Demand",
        "requires_nexus": False,
        "description": "TS-driven work requiring site involvement (e.g., Network TLM)"
    }
}

REQUEST_TYPES = {
    "intake": "New IT service request (never existed before)",
    "incident": "Unplanned interruption to existing IT service",
    "network": "Network/Firewall configuration request",
    "access": "Application or system access request",
    "status": "Status inquiry for existing request"
}

NETWORK_PRIORITIES = {
    "P1": "Urgent/Emergency - Business critical, security concern",
    "P2": "High Priority - Project work requiring focus",
    "P3": "Standard - Normal requests (default)",
    "P4": "Deferred - Back burner requests"
}

COMPONENT_TYPES = [
    "Network", "Firewall", "RF", "Workstations", "Servers",
    "VLAN", "Switch", "LAN/WAN", "Connectivity", "Infrastructure"
]

# Intent patterns for classification
INTENT_PATTERNS = {
    "create_request": [
        "new request", "submit", "create", "need help with",
        "i want to", "can you help me", "looking to", "implement"
    ],
    "report_incident": [
        "not working", "broken", "down", "error", "issue",
        "problem", "stopped", "failed", "crash", "bug"
    ],
    "check_status": [
        "status", "update", "where is", "progress", "track",
        "ritm", "abfz", "ticket", "check on"
    ],
    "get_access": [
        "access", "permission", "login", "account", "ts engage",
        "credentials", "unable to access"
    ],
    "get_help": [
        "how do i", "what is", "explain", "guide", "help",
        "documentation", "process", "procedure"
    ]
}
