import json
from pathlib import Path

ROOT = Path(__file__).parent
ARTICLES_PATH = ROOT / "files" / "article-sources.json"
IMAGES_PATH = ROOT / "images" / "index.json"
OUTPUT_PATH = ROOT / "files" / "image_matches.json"

FALLBACK = {
    "finance": {
        "unsplash": "https://unsplash.com/s/photos/finance",
        "pexels": "https://www.pexels.com/search/finance/"
    },
    "trading": {
        "unsplash": "https://unsplash.com/s/photos/trading",
        "pexels": "https://www.pexels.com/search/trading/"
    },
    "crypto": {
        "unsplash": "https://unsplash.com/s/photos/crypto",
        "pexels": "https://www.pexels.com/search/crypto/"
    },
    "ai": {
        "unsplash": "https://unsplash.com/s/photos/artificial-intelligence",
        "pexels": "https://www.pexels.com/search/artificial-intelligence/"
    }
}

def load_json(path: Path):
    with path.open("r", encoding="utf-8") as f:
        return json.load(f)

def match_local_image(article, catalog):
    keywords = [
        article.get("title", ""),
        article.get("section", ""),
        *article.get("tags", [])
    ]
    keywords = [k.lower() for k in keywords]

    scored = []
    for img in catalog["images"]:
        score = 0
        for tag in img.get("tags", []):
            if tag.lower() in keywords:
                score += 2
        if img.get("type") == "hero" and article.get("priority") == "hero":
            score += 2
        scored.append({"img": img, "score": score})

    scored.sort(key=lambda x: x["score"], reverse=True)
    if scored and scored[0]["score"] > 0:
        return scored[0]["img"]
    return None

def match_fallback(article):
    tags = [t.lower() for t in article.get("tags", [])]
    section = article.get("section", "").lower()

    key = "finance"
    if "crypto" in tags or section == "crypto":
        key = "crypto"
    elif "trading" in tags or section == "trading":
        key = "trading"
    elif "ai" in tags or "ki" in tags or section == "ai":
        key = "ai"

    return FALLBACK[key]

def build_matches():
    articles = load_json(ARTICLES_PATH)["articles"]
    catalog = load_json(IMAGES_PATH)

    results = []
    for art in articles:
        local = match_local_image(art, catalog)
        if local:
            results.append({
                "article_id": art["id"],
                "source": "local",
                "image": {
                    "file": local["file"],
                    "url": local["url"],
                    "type": local.get("type", "inline")
                }
            })
        else:
            fb = match_fallback(art)
            results.append({
                "article_id": art["id"],
                "source": "fallback",
                "fallback": fb
            })

    OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True)
    with OUTPUT_PATH.open("w", encoding="utf-8") as f:
        json.dump({"matches": results}, f, ensure_ascii=False, indent=2)

if __name__ == "__main__":
    build_matches()
    print(f"Wrote {OUTPUT_PATH}")
