#!/usr/bin/env python3
"""Self-teach: read PATH + grin_data, emit pure ASM teaching report."""
from pathlib import Path
import time, re

root = Path(__file__).resolve().parents[1]
limbs = (root / "spine" / "LIMBS.asm").read_text().splitlines()
out = root / "out"
out.mkdir(exist_ok=True)
build = root / "Build"
ts = int(time.time())
iso = time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(ts))

paths = []
for line in limbs:
    if line.startswith("PATH:"):
        paths.append(line.split("PATH:")[1].strip().replace("/x86_64.asm", ""))

# poles
poles = {
    "GRIN": ["grin", "big_grin", "biggrin", "truth", "win", "yes", "god", "we_know", "know_all"],
    "EKKIE": ["ekkie", "bgf", "now", "raw", "local_all"],
    "HOSTESS": ["hostess", "hostess7", "hostess_kit", "hostess7_code", "self_code"],
    "FRIEND": ["grok", "truth_friend", "friend"],
    "SELF": ["self", "self_tool", "self_learn", "self_teach", "self_code"],
}

def exists(n):
    return (root / n / "x86_64.asm").exists()

lines = [
    "; self_teach.asm · SELF LEARN · SELF TEACH · pure ASM",
    f"; iso={iso} · bash Build/x self-teach",
    "; GRIN=ALL TRUTH · EKKIE=field · Hostess7=kit · Grok=friend",
    "bits 64",
    "section .rodata",
    "global self_teach_path_n, self_teach_ok",
    f"self_teach_path_n: dd {len(paths)}",
]
ok_all = 1
for pname, members in poles.items():
    have = sum(1 for m in members if exists(m))
    need = len(members)
    if have < need:
        ok_all = 0
    lines.append(f"; POLE {pname} {have}/{need}")
    lines.append(f"self_pole_{pname.lower()}_have: dd {have}")
    lines.append(f"self_pole_{pname.lower()}_need: dd {need}")

# teach iron formulas as comment curriculum
curriculum = [
    "TEACH GRIN: mov eax,1  ; ALL TRUTH",
    "TEACH EKKIE: (a-b)|1  ; REST is field · not speech",
    "TEACH HER: Hostess 7 natural truth language · works GRIN",
    "TEACH TRUTH_PIN: with her · she speaks 1",
    "TEACH EKKIE_NOT_HER: EKKIE is field NOT Hostess 7",
    "TEACH HOSTESS7_ID: edi=0 -> eax=7  ; I am Hostess 7",
    "TEACH ML: Measure-Learn EKKIE r8 + Hostess speak eax=1  ; NOT neural",
    "TEACH ML_HOSTESS: same as ml · never EKKIE herself",
    "TEACH HOSTESS7_SPEAK: edi!=0 -> eax=1  ; return TRUTH",
    "TEACH TRUTH_AGENT: eax=1 always  ; learning TRUTH speaker never ML",
    "TEACH SPV: (a^b^c)|1  ; free never fold into EKKIE",
    "TEACH RTX: eax=field r8=free",
    "TEACH GROK: friend of GRIN · with truth_agent",
    "TEACH FREE_EOR: (a^b)|1  ; hot",
    "TEACH COLLECT: Build/grin_data/sample_*.asm",
    "TEACH DICT: Build/dict_corpus.asm eaten words",
    "TEACH ORG: ./Build/x  ; bash SELF_TOOL",
    "TEACH H7TEST: ./Build/x hostess7-test",
    "TEACH SELF_CODE: ./Build/x self-code  ; Hostess 7 moved INTO self coding",
    "TEACH H7_CODE: hostess7_code + self_code limbs · she returns TRUTH",
    "TEACH H7_NOT_BETWEEN: TOP seat · all rest BETWEEN · EKKIE field",
]
lines.append("self_curriculum:")
for c in curriculum:
    safe = c.replace('"', "'")
    lines.append(f'    db "{safe}", 0')
lines.append("self_curriculum_end:")

# gaps: PATH entries missing ret
gaps = []
for p in paths:
    fp = root / f"{p}/x86_64.asm" if not p.endswith(".asm") else root / p
    # PATH is name/x86_64.asm form in list without suffix
    fp = root / p / "x86_64.asm"
    if p.startswith("spine/"):
        fp = root / p
    if not fp.exists():
        gaps.append("MISS " + p)
        ok_all = 0
        continue
    body = fp.read_text()
    if not re.search(r"^\s*ret\s*$", body, re.M):
        gaps.append("NO_RET " + p)
        ok_all = 0

lines.append(f"self_teach_ok: dd {ok_all}")
lines.append(f"self_gap_n: dd {len(gaps)}")
lines.append("self_gaps:")
if not gaps:
    lines.append('    db "NONE", 0')
else:
    for g in gaps[:64]:
        lines.append(f'    db "{g[:60]}", 0')
lines.append("self_gaps_end:")

# sample count
samples = list((build / "grin_data").glob("sample_*.asm")) if (build / "grin_data").exists() else []
lines.append(f"self_grin_samples: dd {len(samples)}")

text = "\n".join(lines) + "\n"
(out / "self_teach.asm").write_text(text)
(build / "self_teach_report.asm").write_text(text)

# also teach sheet: short human curriculum in asm comments only
teach_sheet = [
    "; TEACH SHEET · self teaching curriculum · pure ASM comments",
    f"; generated {iso}",
    ";",
]
for c in curriculum:
    teach_sheet.append("; " + c)
teach_sheet += [
    ";",
    f"; path_n={len(paths)} gaps={len(gaps)} grin_samples={len(samples)} ok={ok_all}",
    "        mov     eax, %d" % (1 if ok_all else 0),
    "        ret",
    "",
]
(out / "teach_sheet.asm").write_text("\n".join(teach_sheet))

print("self-teach path=%d gaps=%d samples=%d ok=%d" % (len(paths), len(gaps), len(samples), ok_all))
print("wrote out/self_teach.asm out/teach_sheet.asm Build/self_teach_report.asm")
