"""
Configuracion compartida para los scripts de Talento Humano.

Los secretos se leen desde variables de entorno o desde un archivo .env local
sin versionar. No se deben guardar API keys ni passwords reales en el repo.
"""

from __future__ import annotations

import os
import ssl
from pathlib import Path


BASE_DIR = Path(__file__).resolve().parent


def _load_dotenv(path: Path = BASE_DIR / ".env") -> None:
    if not path.exists():
        return
    for raw_line in path.read_text(encoding="utf-8").splitlines():
        line = raw_line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, value = line.split("=", 1)
        key = key.strip()
        value = value.strip().strip('"').strip("'")
        if key and key not in os.environ:
            os.environ[key] = value


_load_dotenv()


def env_bool(name: str, default: bool = False) -> bool:
    raw = os.getenv(name)
    if raw is None:
        return default
    return raw.strip().lower() in {"1", "true", "yes", "y", "on"}


def require_env(name: str) -> str:
    value = os.getenv(name)
    if value:
        return value
    raise RuntimeError(f"Falta configurar la variable de entorno requerida: {name}")


def require_secrets(*names: str) -> None:
    for name in names:
        require_env(name)


def _normalized_database_url() -> str | None:
    url = os.getenv("DATABASE_URL")
    if not url:
        return None
    return url.replace("postgresql+psycopg://", "postgresql://", 1)


def _search_path_option() -> str | None:
    schema = os.getenv("PG_SCHEMA", "public").strip()
    if not schema:
        return None
    if schema == "public":
        return "-c search_path=public"
    return f"-c search_path={schema},public"


def db_config() -> dict:
    options = _search_path_option()
    database_url = _normalized_database_url()
    if database_url:
        cfg = {"dsn": database_url}
        if options:
            cfg["options"] = options
        return cfg

    cfg = {
        "dbname": os.getenv("PG_DATABASE", "Base de Datos Talento Humano"),
        "user": os.getenv("PG_USER", "postgres"),
        "password": os.getenv("PG_PASSWORD") or os.getenv("PGPASSWORD"),
        "host": os.getenv("PG_HOST", "localhost"),
        "port": int(os.getenv("PG_PORT", "5432")),
    }
    if options:
        cfg["options"] = options
    return cfg


def ssl_context() -> ssl.SSLContext:
    if env_bool("APP_VERIFY_SSL", True):
        return ssl.create_default_context()
    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE
    return ctx


API_BASE = os.getenv("NOMINA_API_BASE", "https://api.innfinancial.cloud/api/v1")
NOMINA_API_KEY = os.getenv("NOMINA_API_KEY", "")

PYG_URL = os.getenv("PYG_API_URL", "https://app.faranda.online/rm/reportePyg/comparativo/")
PYG_API_KEY = os.getenv("PYG_API_KEY", "")
