"""SOAGILA local configuration for MCP server mode."""

import os
import hashlib
from pathlib import Path
from functools import lru_cache

from pydantic_settings import BaseSettings


class Settings(BaseSettings):
    """SOAGILA MCP Server settings.

    Settings are loaded from environment variables passed by the VS Code extension.
    """
    # Project
    project_cwd: str = os.getcwd()

    # App
    app_name: str = "SOAGILA for Code"
    app_version: str = "0.8.0"

    # Licensing
    tier: str = "free"  # free | pro | enterprise

    # Memory defaults
    working_memory_default_ttl: int = 1800  # 30 minutes
    decay_threshold: float = 0.15
    promotion_min_count: int = 5
    decay_cycle_interval: int = 300  # 5 minutes

    # Encryption
    encryption_mode: str = "simulated"  # simulated | real_he

    # Embedding
    embedding_model: str = "all-MiniLM-L6-v2"

    # PMP — Predictive Memory Priming
    pmp_enabled: bool = True
    pmp_cache_ttl: int = 300              # seconds (5 min default)
    pmp_relevance_threshold: float = 0.3  # min relevance for primed memories
    pmp_prediction_depth: int = 5         # topics to predict
    pmp_max_episodic: int = 30            # max episodic memories to prime
    pmp_auto_prime_on_recall: bool = True  # auto-prime after recall miss
    pmp_background_prime: bool = True     # enable background priming cycle

    # Memory Inheritance
    inheritance_enabled: bool = True
    inheritance_confidence_threshold: float = 0.7   # min confidence for global promotion
    inheritance_confidence_tax: float = 0.1          # confidence reduction per inheritance level
    inheritance_recall_weight: float = 0.7           # weight for inherited memories in recall
    inheritance_max_global_results: int = 5          # max inherited memories per recall

    # Telemetry
    telemetry_enabled: bool = True
    telemetry_detailed: bool = False  # Model C opt-in
    telemetry_endpoint: str = "https://soagila-cloud-backend.sonat-ciftcioglu.workers.dev"

    # Logging
    log_level: str = "INFO"

    model_config = {"env_prefix": "SOAGILA_", "case_sensitive": False}


@lru_cache()
def get_settings() -> Settings:
    return Settings()


def get_soagila_home() -> Path:
    """Get the SOAGILA home directory (~/.soagila/)."""
    home = Path.home() / ".soagila"
    home.mkdir(parents=True, exist_ok=True)
    return home


def get_project_hash(cwd: str | None = None) -> str:
    """Compute project hash from absolute path (case-normalized on Windows)."""
    if cwd is None:
        cwd = os.environ.get("SOAGILA_PROJECT_CWD", os.getcwd())
    abs_path = os.path.normcase(os.path.abspath(cwd))  # lowercase on Windows
    return hashlib.sha256(abs_path.encode()).hexdigest()[:16]


def get_project_dir(cwd: str | None = None) -> Path:
    """Get the project-specific SOAGILA directory."""
    project_hash = get_project_hash(cwd)
    project_dir = get_soagila_home() / "projects" / project_hash
    project_dir.mkdir(parents=True, exist_ok=True)
    return project_dir


def get_project_db_path(cwd: str | None = None) -> str:
    """Get the SQLite database path for the current project."""
    return str(get_project_dir(cwd) / "soagila.db")
