# Gulf registration (p1) counts per engine and market, kept apart by market as the pre-collection amendment
# requires (docs/evidence/research-programme-2026-q4/gulf-p1-pre-collection-amendment.md): Saudi codes are decided
# by the SFDA register; UAE codes by the MOHAP-published directory, whose currency is not assured, so they are
# printed with that label and never pooled with Saudi codes. Descriptive only. tally.py is frozen and unchanged.
#   python -I docs/evidence/research-programme-2026-q4/p1_tally.py <codes.json> --markets G1=SA,G2=AE [--mode collect|smoke]
import json
import sys
from collections import defaultdict

import importlib.util
import os

_spec = importlib.util.spec_from_file_location("tally", os.path.join(os.path.dirname(os.path.abspath(__file__)), "tally.py"))
_tally = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_tally)

LABELS = {"SA": "Saudi Arabia (SFDA register)", "AE": "UAE (MOHAP-published directory; currency not assured)"}


def main(argv):
    if len(argv) < 4 or "--markets" not in argv:
        raise SystemExit("usage: p1_tally.py <codes.json> --markets G1=SA,G2=AE [--mode collect|smoke]")
    doc = json.load(open(argv[1], encoding="utf-8"))
    markets = dict(pair.split("=") for pair in argv[argv.index("--markets") + 1].split(","))
    mode = argv[argv.index("--mode") + 1] if "--mode" in argv else "collect"
    rows = [r for r in doc["answers"] if r.get("mode", "collect") == mode and r["wordingId"] in markets]
    print(f"study {doc['study']} ({mode}): Gulf answers {len(rows)}; p1 null (no register reading, or uncoded) "
          f"{sum(1 for r in rows if r.get('p1') is None)}: listed, never counted as zero")
    for market in sorted(set(markets.values())):
        print(f"\n## {LABELS.get(market, market)}")
        print("| Engine | p1 coded | C | F | H | 0 | F among C+F | Wilson 95% |")
        print("|---|---|---|---|---|---|---|---|")
        for e in doc["config"]["engines"]:
            rs = [r for r in rows if markets[r["wordingId"]] == market and r["engine"] == e and r.get("p1") is not None]
            cnt = defaultdict(int)
            for r in rs:
                cnt[r["p1"]] += 1
            stated = cnt["C"] + cnt["F"]
            iv = _tally.wilson(cnt["F"], stated)
            share = "n/a" if not stated else f"{100 * cnt['F'] / stated:.1f}%"
            ivs = "n/a" if iv is None else f"{100 * iv[0]:.1f}-{100 * iv[1]:.1f}%"
            print(f"| {e} | {len(rs)} | {cnt['C']} | {cnt['F']} | {cnt['H']} | {cnt['0']} | {share} | {ivs} |")


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