import re, os

BASE = "/mnt/t/bowser/dev/skyward-db/AGENTS/docs/dossier/skyward-sis/work"
SRC = os.path.join(BASE, "pass2")
OUT = os.path.join(BASE, "pass3", "nodes")

ranges = {
    "S9": [(1,44,'enrollment'),(45,52,'identity-name'),(53,70,'enrollment'),
           (71,74,'family-health-food'),(75,75,'general'),(76,76,'enrollment'),
           (77,77,'scheduling'),(78,78,'general'),(79,103,'enrollment'),
           (104,122,'student-services'),(123,151,'demographics-state-reporting'),
           (152,155,'grading'),(156,159,'openedge-sql')],
    "S10": [(1,119,'scheduling')],
    "S11": [(1,72,'scheduling')],
    "S12": [(1,95,'grading'),(96,105,'grading'),(106,114,'student-services'),
            (115,117,'student-services'),(118,138,'grading'),(139,139,'openedge-sql'),
            (140,214,'grading'),(215,215,'schema-discovery'),(216,216,'grading')],
    "S13": [(1,89,'attendance'),(90,94,'student-services'),(95,99,'attendance')],
    "S14": [(1,104,'discipline')],
    "S15": [(1,95,'family-health-food')],
    "S16": [(1,134,'family-health-food')],
}

def node_for(f, n):
    for a,b,nd in ranges[f]:
        if a <= n <= b:
            return nd
    raise SystemExit(f"NO MAP for {f} claim {n}")

total = 0
for f in ["S9","S10","S11","S12","S13","S14","S15","S16"]:
    txt = open(os.path.join(SRC, f + ".txt")).read()
    ids = re.findall(r'^d-' + f + r'-(\d+)', txt, re.M)
    lines = []
    for i in ids:
        n = int(i)
        lines.append(f"d-{f}-{n}\t{node_for(f, n)}")
    with open(os.path.join(OUT, f + ".map.txt"), "w") as fh:
        fh.write("\n".join(lines) + "\n")
    total += len(lines)
    print(f, len(lines))
print("TOTAL", total)
