#!/usr/bin/env python3
"""Rerun this use case: how a target account list narrows, filter by filter.

    export METIX_KEY=metix_xxxxxxxxxxxx   (or put it in the repository's .env)
    python3 cases/build-target-account-list/fetch.py

Counts only. The ledger adds one condition at a time from queries/accounts.json;
the state table splits the final list by headquarters state. Companies are not
people, so no count is suppressed.
"""

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=20)
    clauses = load_query(HERE, "accounts")["where"]["all"]
    # The two headcount bounds form one step, so the ledger has four rows.
    cuts = [1, 2, 4, 5]
    ledger = [
        {"group": group, "count": platform.count("companies", {"all": clauses[:cut]})}
        for group, cut in zip(["country", "industry", "size", "growth"], cuts)
    ]
    query = "queries/accounts.json"
    write_json(HERE, "ledger.json", aggregate("companies", platform.snapshot, query, ledger))

    states = json.loads((HERE / "states.json").read_text(encoding="utf-8"))
    rows = [
        {
            "group": state,
            "count": platform.count(
                "companies", {"all": [*clauses, {"field": "headquarters.state", "eq": state}]}
            ),
        }
        for state in states
    ]
    listed = ledger[-1]["count"]
    rows.append({"group": "other", "count": listed - sum(r["count"] for r in rows)})
    write_json(HERE, "states.json", aggregate("companies", platform.snapshot, query, rows, accounts_count=listed))
    write_json(HERE, "receipt.json", platform.receipt())
    print(ledger, rows, f"{platform.spent()} API Credits")
    return 0


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