#!/usr/bin/env python3
"""Rerun this use case: which accounts on a list are hiring for one role.

    export METIX_KEY=metix_xxxxxxxxxxxx   (or put it in the repository's .env)
    python3 cases/find-accounts-hiring-for-a-role/fetch.py

Two counts per account in accounts.json: its open postings for the role in
queries/role.json, and all its open postings, so a big hirer does not look like
a strong signal only because it posts a lot. Counts only; no posting is read.
"""

from __future__ import annotations

import json
import sys
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


def main() -> int:
    platform = Platform(max_credits=30)
    role = load_query(HERE, "role")["where"]["all"]
    open_only = [c for c in role if c.get("field") == "is_open"]
    accounts = json.loads((HERE / "account-list.json").read_text(encoding="utf-8"))
    rows = []
    for company in accounts:
        at = {"field": "company.name", "eq": company}
        rows.append(
            {
                "company": company,
                "role_count": platform.count("jobs", {"all": [at, *role]}),
                "open_count": platform.count("jobs", {"all": [at, *open_only]}),
            }
        )
    rows.sort(key=lambda r: (-r["role_count"], r["company"]))
    write_json(HERE, "accounts.json", aggregate("jobs", platform.snapshot, "queries/role.json", rows))
    write_json(HERE, "receipt.json", platform.receipt())
    print(rows, f"{platform.spent()} API Credits")
    return 0


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