"""
config_loader.py

Single source of truth for reading THIS project's own config.json and
.env credentials (screener/trade -- separate files, separate process,
no relationship to screener/premarket's config_loader.py of the same
name, despite the identical pattern). Every other module here imports
get_config() / get_env() from here instead of touching os.environ or
config.json directly.
"""

import json
import os
from pathlib import Path
from functools import lru_cache

BASE_DIR = Path(__file__).resolve().parent
CONFIG_PATH = BASE_DIR / "config.json"
ENV_PATH = BASE_DIR / ".env"


def _load_dotenv(path: Path):
    """Minimal .env loader (no external dependency required)."""
    if not path.exists():
        return
    with open(path, "r") as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith("#") or "=" not in line:
                continue
            key, _, value = line.partition("=")
            key = key.strip()
            value = value.strip().strip('"').strip("'")
            os.environ.setdefault(key, value)


_load_dotenv(ENV_PATH)


@lru_cache(maxsize=1)
def get_config() -> dict:
    with open(CONFIG_PATH, "r") as f:
        return json.load(f)


def reload_config() -> dict:
    """Force re-read of config.json (useful if tuning live without restart)."""
    get_config.cache_clear()
    return get_config()


class EnvConfig:
    """Wraps required Alpaca credentials with clear failure if missing."""

    def __init__(self):
        self.api_key = os.environ.get("ALPACA_API_KEY")
        self.secret_key = os.environ.get("ALPACA_SECRET_KEY")
        self.base_url = os.environ.get("APCA_API_BASE_URL", "https://paper-api.alpaca.markets")
        self.data_url = os.environ.get("ALPACA_DATA_URL", "https://data.alpaca.markets")

    def validate(self):
        missing = []
        if not self.api_key:
            missing.append("ALPACA_API_KEY")
        if not self.secret_key:
            missing.append("ALPACA_SECRET_KEY")
        if missing:
            raise EnvironmentError(
                f"Missing required environment variables: {', '.join(missing)}. "
                f"Copy .env.example to .env and fill in your Alpaca credentials."
            )


@lru_cache(maxsize=1)
def get_env() -> EnvConfig:
    return EnvConfig()


def cfg(*keys, default=None):
    """Convenience getter for nested config values, e.g. cfg("universe", "price_min")."""
    node = get_config()
    for k in keys:
        if not isinstance(node, dict) or k not in node:
            return default
        node = node[k]
    return node
