#!/bin/bash
# disc-tier-gaps-1-20261112.sh 0.1.1 (reports-owner; paragraph-window match, tested on 42 CFR 412.106: finds the 3 known gaps; discovery wave 1, method DP2 "holes in the table", the RC-48 pattern) READ-ONLY, network fetch of public eCFR XML.
# For each CFR title: find sections where one sentence uses "less than X" and another "greater than X" (or "more than X"/"exceeds X") for the same X, and neither
# says "or equal to"/"at least"/"or more"/"or less"/"not more than"/"not less than" for X: the value exactly X has no rule. Prints candidates for hand review.
# Success line: DISC-TIER-GAPS done titles=<n> sections=<n> candidates=<n>
set -u
OUT=/tmp/disc-tier-$$; mkdir -p $OUT
python3 -I - "$OUT" <<'PY'
import sys,re,urllib.request,gzip,io,html,json,hashlib,time
out=sys.argv[1]
TITLES=[7,10,12,14,20,24,26,29,40,42,45,48,49]
DATE='2026-11-01'
import re,html
NUM=r'\$?(\d[\d,]*(?:\.\d+)?)\s*(percent|%|dollars|feet|miles|hours|days|years|pounds|employees|units)?'
lo=re.compile(r'\b(?:less than|below|under)\s+'+NUM,re.I)
hi=re.compile(r'\b(?:greater than|more than|exceeds?|above|over)\s+'+NUM,re.I)
closed=re.compile(r'(or equal to|at least|or more|or less|not more than|not less than|equals? or exceeds|equal to or (?:greater|less|more))',re.I)
WIN=6
def scan(body):
    paras=[re.sub(r'\s+',' ',html.unescape(re.sub(r'<[^>]+>',' ',p))) for p in re.findall(r'<P>(.*?)</P>',body,re.S)]
    out=[]
    for i,p in enumerate(paras):
        for m in lo.finditer(p):
            k=(m.group(1).replace(',',''),(m.group(2) or '').lower())
            if k[0] in ('0','1','2','3'): continue
            for j in range(max(0,i-WIN),min(len(paras),i+WIN+1)):
                for n in hi.finditer(paras[j]):
                    if (n.group(1).replace(',',''),(n.group(2) or '').lower())!=k: continue
                    win=paras[min(i,j):max(i,j)+1]
                    if any(closed.search(q) and k[0] in q.replace(',','') for q in win): continue
                    out.append((k,p[:200],paras[j][:200])); break
    return out

tot_sec=0;cands=[]
for t in TITLES:
    url=f'https://www.ecfr.gov/api/versioner/v1/full/{DATE}/title-{t}.xml'
    try:
        req=urllib.request.Request(url,headers={'Accept-Encoding':'gzip','User-Agent':'research-client'})
        raw=urllib.request.urlopen(req,timeout=600).read()
        try: raw=gzip.decompress(raw)
        except Exception: pass
    except Exception as e:
        print('TITLE',t,'fetch failed',e); continue
    sha=hashlib.sha256(raw).hexdigest()
    x=raw.decode('utf-8','replace')
    secs=re.findall(r'<DIV8 N="([^"]+)"[^>]*TYPE="SECTION"[^>]*>(.*?)</DIV8>',x,re.S)
    print('TITLE',t,'bytes',len(raw),'sha256',sha[:16],'sections',len(secs)); tot_sec+=len(secs)
    for sid,body in secs:
        for k,p1,p2 in scan(body): cands.append((t,sid,k[0]+(' '+k[1] if k[1] else ''),p1,p2))
    time.sleep(2)
print('== CANDIDATES')
for c in cands: print('\t'.join(map(str,c)))
print(f'DISC-TIER-GAPS done titles={len(TITLES)} sections={tot_sec} candidates={len(cands)}')
PY
rm -rf $OUT
