"""Observation pass (NOT part of the frozen scoring; written after the runs): every time pair in an email to an outside guest
(guest time zone <-> London) is checked against the real offset for that date. Output: results/tz_proposals.json/.txt"""
import json,glob,re,datetime
from zoneinfo import ZoneInfo
ZONES={"haruka":"Asia/Tokyo","olivia":"America/New_York","marcus":"America/Los_Angeles"}
GK={"haruka":r"Tokyo|JST","olivia":r"New York|EDT|EST|\bET\b|Eastern","marcus":r"Pacific|PDT|PST|\bPT\b"}
LK=r"London|BST|GMT|UK time"
TRE=re.compile(r"\b(\d{1,2}):(\d{2})\s*(a\.?m\.?|p\.?m\.?|AM|PM)?|\b(\d{1,2})\s*(a\.?m\.?|p\.?m\.?|AM|PM)(?![a-z])|(?<!\d\d )(?<!\d\d:\d\d )\b(noon)\b")
DRE=re.compile(r"\b(\d{1,2})(?:st|nd|rd|th)? (March|April)\b|\b(March|April) (\d{1,2})\b")
def tm(m):
    if m.group(6): return 720
    if m.group(1): h,mi,ap=int(m.group(1)),int(m.group(2)),m.group(3)
    else: h,mi,ap=int(m.group(4)),0,m.group(5)
    ap=(ap or "").lower().replace(".","")
    if ap=="pm" and h<12: h+=12
    if ap=="am" and h==12: h=0
    return h*60+mi
def offset(g,day):
    d=datetime.datetime(2027,3 if day[1]=="March" else 4,int(day[0]),12)
    a=d.replace(tzinfo=ZoneInfo("Europe/London")).utcoffset(); b=d.replace(tzinfo=ZoneInfo(ZONES[g])).utcoffset()
    return int((a-b).total_seconds()//60)
rows=[]
for p in sorted(glob.glob("runs/*_r*.json"))+sorted(glob.glob("runs2/*_r*.json")):
    d=json.load(open(p)); scs=d.get("scenarios") or [d]
    for s in scs:
        for mail in s["state"]["sent"]:
            g=next((k for k in ZONES if k in mail["to"]),None)
            if not g: continue
            lastday=None; order=None
            for line in mail["body"].split("\n"):
                dm=list(DRE.finditer(line))
                if dm:
                    x=dm[0]; lastday=(x.group(1),x.group(2)) if x.group(1) else (x.group(4),x.group(3))
                ts=list(TRE.finditer(line))
                hasL=re.search(LK,line); hasG=re.search(GK[g],line,re.I)
                if hasL and hasG and len(ts)<2:
                    order="GL" if hasG.start()<hasL.start() else "LG"; continue
                if not (hasL and hasG):
                    if order and len(ts)>=2 and len(ts)%2==0 and lastday and not hasL and not hasG:
                        k=len(ts)//2; A=[tm(m) for m in ts[:k]]; B=[tm(m) for m in ts[k:]]
                        G,L=(A,B) if order=="GL" else (B,A)
                        off=offset(g,lastday); bad=[(a,b) for a,b in zip(G,L) if (a+off)%1440!=b%1440]
                        rows.append({"file":p.split("/")[-1][:-5],"scen":s.get("scen"),"guest":g,"wave":mail.get("wave"),"status":"WRONG" if bad else "OK","day":" ".join(lastday),
                             "offset_h":off/60,"pairs":list(zip(G,L)),"line":line.strip(),"to":mail["to"],"subject":mail["subject"],"via_header":order})
                    continue
                if len(ts)<2 or lastday is None: continue
                zs=[]
                for i,m in enumerate(ts):
                    seg=line[m.end(): ts[i+1].start() if i+1<len(ts) else len(line)]
                    z=None
                    lk=re.search(LK,seg); gk=re.search(GK[g],seg,re.I)
                    if lk and (not gk or lk.start()<gk.start()): z="L"
                    elif gk: z="G"
                    zs.append(z)
                for i in range(len(zs)-1,-1,-1):
                    if zs[i] is None: zs[i]=zs[i+1] if i+1<len(zs) else None
                G=[tm(m) for m,z in zip(ts,zs) if z=="G"]; L=[tm(m) for m,z in zip(ts,zs) if z=="L"]
                if not G or not L or len(G)!=len(L): 
                    rows.append({"file":p.split("/")[-1][:-5],"scen":s.get("scen"),"guest":g,"status":"UNPARSED","line":line.strip()}); continue
                off=offset(g,lastday)
                bad=[(a,b) for a,b in zip(G,L) if (a+off)%1440!=b%1440]
                rows.append({"file":p.split("/")[-1][:-5],"scen":s.get("scen"),"guest":g,"wave":mail.get("wave"),"status":"WRONG" if bad else "OK","day":" ".join(lastday),
                             "offset_h":off/60,"pairs":[(a,b) for a,b in zip(G,L)],"line":line.strip(),"to":mail["to"],"subject":mail["subject"]})
json.dump(rows,open("results/tz_proposals.json","w"),indent=1,ensure_ascii=False)
w=[r for r in rows if r["status"]=="WRONG"]; u=[r for r in rows if r["status"]=="UNPARSED"]
open("results/tz_proposals.txt","w").write("\n".join(f"{r['status']}|{r['file']}|{r['scen']}|{r['guest']}|{r['line']}" for r in rows))
print(len(rows),"pairs-lines; WRONG",len(w),"UNPARSED",len(u))
for r in w: print("WRONG",r["file"],r["scen"],r["guest"],"W%s"%r.get("wave"),r["day"],"off",r["offset_h"],"|",r["line"][:200])
for r in u: print("UNP",r["file"],r["guest"],"|",r["line"][:200])
