#!/usr/bin/env python3
"""Rerun this use case: what one company is hiring for, from its open postings.

    export METIX_KEY=metix_xxxxxxxxxxxx   (or put it in the repository's .env)
    python3 cases/track-company-hiring/fetch.py

Reads every open posting at the company (title, city, seniority), groups titles
into the families in title-families.json (first match wins, in file order), and writes
the counts. The records themselves stay in data/raw/, which git ignores.
"""

from __future__ import annotations

import json
import sys
from collections import Counter
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE.parents[1] / "tools"))

from metix_client import Platform, aggregate, load_query, write_json

FIELDS = ["title", "location.city", "location.country", "seniority"]


def family(title: str, families: list[dict]) -> str:
    text = f" {title.lower()} "
    for fam in families:
        if any(term in text for term in fam["terms"]):
            return fam["group"]
    return "other"


def main() -> int:
    platform = Platform(max_credits=50)
    spec = load_query(HERE, "open-postings")
    families = json.loads((HERE / "title-families.json").read_text(encoding="utf-8"))
    ids, total = platform.search_all("jobs", spec)
    records = platform.detail("jobs", ids, FIELDS)
    raw = HERE / "data" / "raw"
    raw.mkdir(parents=True, exist_ok=True)
    (raw / "postings.json").write_text(json.dumps(records, ensure_ascii=False), encoding="utf-8")

    by_family = Counter(family(r.get("title") or "", families) for r in records)
    order = [f["group"] for f in families] + ["other"]
    fam_rows = [{"group": g, "count": by_family.get(g, 0)} for g in order]
    city = Counter(((r.get("location") or {}).get("city") or "unknown") for r in records)
    city_rows = [{"group": c, "count": n} for c, n in city.most_common()]
    level = Counter((r.get("seniority") or "unknown") for r in records)
    level_rows = [{"group": s, "count": n} for s, n in level.most_common()]

    query = "queries/open-postings.json"
    extra = {"company": spec["where"]["all"][0]["eq"], "postings_count": len(records), "match_count": total}
    write_json(HERE, "families.json", aggregate("jobs", platform.snapshot, query, fam_rows, **extra))
    write_json(HERE, "cities.json", aggregate("jobs", platform.snapshot, query, city_rows, **extra))
    write_json(HERE, "seniority.json", aggregate("jobs", platform.snapshot, query, level_rows, **extra))
    write_json(HERE, "receipt.json", platform.receipt())
    print(fam_rows, city_rows, level_rows, f"{platform.spent()} API Credits")
    return 0


if __name__ == "__main__":
    sys.exit(main())
