"""API key authentication for the ingest server.

Keys are loaded from the QC_TRACE_API_KEYS environment variable
(comma-separated) or from ~/.quickcall-trace/config.json.
"""

from __future__ import annotations

import json
import logging
import os
from pathlib import Path

logger = logging.getLogger(__name__)

CONFIG_PATH = Path.home() / ".quickcall-trace" / "config.json"


def load_api_keys() -> set[str]:
    """Load allowed API keys from env var or config file.

    Returns an empty set if no keys are configured (auth disabled).
    """
    keys: set[str] = set()

    env_keys = os.environ.get("QC_TRACE_API_KEYS", "")
    if env_keys:
        keys.update(k.strip() for k in env_keys.split(",") if k.strip())

    if CONFIG_PATH.exists():
        try:
            config = json.loads(CONFIG_PATH.read_text())
            if config.get("api_key"):
                keys.add(config["api_key"])
        except (json.JSONDecodeError, OSError):
            logger.warning("Failed to read config from %s", CONFIG_PATH)

    return keys


def validate_api_key(key: str | None, allowed_keys: set[str]) -> bool:
    """Check if the provided key is in the allowlist.

    If allowed_keys is empty, auth is disabled (returns True).
    """
    if not allowed_keys:
        return True
    if not key:
        return False
    return key in allowed_keys


def load_cors_origin() -> str:
    """Load the allowed CORS origin.

    Reads QC_TRACE_CORS_ORIGIN env var, defaults to http://localhost:3000.
    """
    return os.environ.get("QC_TRACE_CORS_ORIGIN", "http://localhost:3000")
