
from __future__ import annotations

import json
from pathlib import Path
from typing import Any

BASE_DIR = Path(__file__).resolve().parents[1]
DATA_DIR = BASE_DIR / "data"
CONFIG_FILE = DATA_DIR / "agency_territory.json"
SOURCES_FILE = DATA_DIR / "api_sources.json"


def load_agency_config() -> dict[str, Any]:
    with CONFIG_FILE.open("r", encoding="utf-8") as f:
        return json.load(f)


def load_sources_catalog() -> dict[str, Any]:
    with SOURCES_FILE.open("r", encoding="utf-8") as f:
        return json.load(f)


def agency_epci_codes() -> list[str]:
    return [item["code"] for item in load_agency_config().get("epci_codes", [])]


def agency_epcis() -> list[dict[str, str]]:
    return load_agency_config().get("epci_codes", [])


def is_code_allowed(code: str | None, allowed_communes: set[str] | None = None, allowed_epcis: set[str] | None = None) -> bool:
    if not code:
        return False
    code = str(code)
    if allowed_communes and code in allowed_communes:
        return True
    if allowed_epcis and code in allowed_epcis:
        return True
    return False
