"""EO 14434の本文で、旧称（Artificial Intelligence / AI）と新称（Super Intelligence / SI）を数える。

使い方: python3 eo_count.py   → data/eo_count.json
本文は連邦官報（91 FR 63129）のテキスト。「By the authority vested…」から署名の手前までを本文として数える。
"""
import json
import re
import urllib.request
from pathlib import Path

URL = "https://www.federalregister.gov/documents/full_text/text/2026/10/02/2026-20321.txt"
raw = urllib.request.urlopen(urllib.request.Request(URL, headers={"User-Agent": "Mozilla/5.0"}), timeout=60).read().decode()
text = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", raw))
body = text[text.index("By the authority"): text.index("(Presidential Sig.)")]
Path(__file__).parent.joinpath("data", "eo-14434-body.txt").write_text(body + "\n")
sections = re.split(r"(?=Section 1\. |Sec\. [234]\. )", body)
result = {"words": len(body.split()), "total": {}, "by_section": {}}
pat = {
    "artificial_intelligence": r"[Aa]rtificial [Ii]ntelligence",
    "super_intelligence": r"Super Intelligence",
    "AI": r"``AI''",
    "SI": r"``SI''",
}
for k, p in pat.items():
    result["total"][k] = len(re.findall(p, body))
for s in sections:
    m = re.match(r"(Section 1|Sec\. [234])", s)
    if not m:
        continue
    result["by_section"][m.group(1)] = {k: len(re.findall(p, s)) for k, p in pat.items()}
Path(__file__).parent.joinpath("data", "eo_count.json").write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
print(json.dumps(result, ensure_ascii=False, indent=2))
