import os
from pathlib import Path
import yaml

def _read_yaml(path: str) -> dict:
    with open(path, "r", encoding="utf-8") as f:
        return yaml.safe_load(f) or {}

def deep_merge(a: dict, b: dict) -> dict:
    out = dict(a or {})
    for k, v in (b or {}).items():
        if isinstance(v, dict) and isinstance(out.get(k), dict):
            out[k] = deep_merge(out[k], v)
        else:
            out[k] = v
    return out

def load_settings() -> dict:
    cfg_path = os.getenv("CONFIG_FILE", "/config/config.yaml")
    settings = _read_yaml(cfg_path)

    secrets_path = os.getenv("SECRETS_FILE", "")
    if secrets_path and Path(secrets_path).exists():
        secrets = _read_yaml(secrets_path)
        settings = deep_merge(settings, secrets)

    # fallback paths (coerenti con compose)
    settings.setdefault("paths", {})
    settings["paths"].setdefault("dataset", os.getenv("DATASET_PATH", "/data/fingerprint.parquet"))
    settings["paths"].setdefault("model", os.getenv("MODEL_PATH", "/models/model.joblib"))

    return settings
