"""데모 카탈로그 + 상품 데이터 로더."""
from __future__ import annotations

import json
from functools import lru_cache
from typing import Any

from app.config import settings


@lru_cache(maxsize=1)
def load_catalog() -> dict[str, Any]:
    path = settings.data_path / "demo-catalog.json"
    with open(path, encoding="utf-8") as f:
        return json.load(f)


_DATA_FILES = ("kodex-200-demo-data.json", "woori-etf-demo-data.json")


@lru_cache(maxsize=1)
def load_product_data() -> dict[str, Any]:
    merged: dict[str, Any] = {"productSearch": [], "products": {}}
    for name in _DATA_FILES:
        path = settings.data_path / name
        if not path.exists():
            continue
        with open(path, encoding="utf-8") as f:
            d = json.load(f)
        merged["productSearch"].extend(d.get("productSearch", []))
        merged["products"].update(d.get("products", {}))
    return merged


def search_products(query: str) -> list[dict[str, Any]]:
    q = (query or "").strip().lower()
    items = load_product_data().get("productSearch", [])
    if not q:
        return items
    out = []
    for it in items:
        haystack = " ".join(
            str(it.get(k, "")) for k in ("fund_code", "fund_name", "search_keyword", "display_name")
        ).lower()
        if q in haystack:
            out.append(it)
    return out


def get_product(fund_code: str) -> dict[str, Any] | None:
    return load_product_data().get("products", {}).get(fund_code)
