"""
BIBIVIDI — Configuration
Loads settings from environment / .env file.
"""
from __future__ import annotations

from pathlib import Path
from typing import Literal

from pydantic import Field, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    model_config = SettingsConfigDict(
        # ~/.bibividi/.env is the user-writable config (written by the UI wizard).
        # .env in CWD is the developer/CI override.  Later files win.
        env_file=[str(Path.home() / ".bibividi" / ".env"), ".env"],
        env_file_encoding="utf-8",
        env_prefix="BIBIVIDI_",
        case_sensitive=False,
    )

    # ── Proxy ─────────────────────────────────────────────────
    proxy_host: str = "127.0.0.1"
    proxy_port: int = 8080
    proxy_ssl: bool = False
    tunnel_port: int = 8443

    # ── Target AI APIs ────────────────────────────────────────
    target_apis: list[str] = Field(
        default=[
            "api.anthropic.com",
            "api.openai.com",
            "generativelanguage.googleapis.com",
            "api.groq.com",
            "api.together.xyz",
            "api.mistral.ai",
        ]
    )
    # When true, allows localhost / 127.0.0.1 targets (e.g. Ollama :11434).
    # Keep false in production to prevent SSRF via crafted Host headers.
    allow_local_apis: bool = False   # BIBIVIDI_ALLOW_LOCAL_APIS
    # Override the daily token quota for quota-mode display (status, simulate).
    # If unset, the known free-tier limit for the detected model is used.
    # Set to your Ollama host's effective limit or a custom provider's quota.
    quota_daily_tokens: int | None = Field(default=None)  # BIBIVIDI_QUOTA_DAILY_TOKENS

    # ── Matching engine ───────────────────────────────────────
    match_threshold: float = 0.75
    embedding_model: str = "all-MiniLM-L6-v2"
    max_script_runtime_s: float = 10.0

    # ── Storage ───────────────────────────────────────────────
    data_dir: Path = Field(default_factory=lambda: Path.home() / ".bibividi")
    db_path: Path | None = Field(default=None)

    # ── Logging ───────────────────────────────────────────────
    log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR"] = "INFO"
    log_requests: bool = False

    # ── Stats ─────────────────────────────────────────────────
    track_savings: bool = True

    # ── Dry run ───────────────────────────────────────────────
    dry_run: bool = False   # log savings but don't inject condensed result

    # ── Notifications ─────────────────────────────────────────
    slack_webhook: str | None = Field(default=None)   # BIBIVIDI_SLACK_WEBHOOK

    # ── Generator ─────────────────────────────────────────────
    generator_enabled: bool = True
    generator_api_key: str | None = Field(default=None)
    generator_model: str = "claude-haiku-4-5-20251001"
    generator_provider: Literal["anthropic", "openai"] = "anthropic"
    generator_api_base: str | None = Field(default=None)

    # ── Chaining (BSS 1.1) ────────────────────────────────────
    enable_chains: bool = False             # BIBIVIDI_ENABLE_CHAINS
    max_chain_depth: int = 10               # BIBIVIDI_MAX_CHAIN_DEPTH
    max_chain_runtime_s: float = 0.0        # 0 = 3× max_script_runtime_s

    # ── Auto-assembly (BSS 2.0) ───────────────────────────────
    enable_auto_assembly: bool = False      # BIBIVIDI_ENABLE_AUTO_ASSEMBLY

    # ── Badge ─────────────────────────────────────────────────
    badge_token: str | None = Field(default=None)  # BIBIVIDI_BADGE_TOKEN; None = public

    # ── Billing ───────────────────────────────────────────────
    stripe_api_key: str | None = Field(default=None)   # BIBIVIDI_STRIPE_API_KEY
    billing_tier: str = "pro"   # BIBIVIDI_BILLING_TIER: free|pro|growth|enterprise
    billing_api_url: str = "https://api.bibividi.ai"   # BIBIVIDI_BILLING_API_URL

    # ── Mailer (quarterly digest email) ───────────────────────────────────────
    mailer_provider: str = "resend"         # BIBIVIDI_MAILER_PROVIDER: resend|postmark
    mailer_api_key: str | None = Field(default=None)  # BIBIVIDI_MAILER_API_KEY
    mailer_from: str = "BIBIVIDI <noreply@localhost>"  # BIBIVIDI_MAILER_FROM
    mailer_to: str | None = Field(default=None)   # BIBIVIDI_MAILER_TO (recipient)

    @model_validator(mode="after")
    def resolve_paths(self) -> Settings:
        self.data_dir.mkdir(parents=True, exist_ok=True)
        if self.db_path is None:
            self.db_path = self.data_dir / "library.db"
        if self.generator_api_base is None:
            self.generator_api_base = (
                "https://api.openai.com"
                if self.generator_provider == "openai"
                else "https://api.anthropic.com"
            )
        if self.max_chain_runtime_s <= 0.0:
            self.max_chain_runtime_s = self.max_script_runtime_s * 3
        return self


# Singleton — import this everywhere
settings = Settings()
