# -*- coding: utf-8 -*-
"""Recherche-Helfer: kreuzt jedes NeedsInfo/Open-Ticket gegen ALLE Quellen
(_rpro3.db per Name+DOB, .mxp-Backup) und zeigt, was verfügbar ist —
damit Rückfragen nur bleiben, wo wirklich nichts gefunden wird."""
import json, urllib.request, re, sys
import compare_rpro3 as C
import rpro3_mxp

DB = "_rpro3.db"
BACKUP = r"C:\Users\gulum\dev\RennmausPro IIIb 06.06.26.backup"

def norm(s):
    s = (s or "").lower()
    for suf in [" von den kleinen chaoten", " v.d. kleinen chaoten", " von den", " of ", " gen. ", " gen "]:
        pass
    s = re.split(r"\bvon\b|\bof\b|\bv\.d\.\b|\bgen\.?\b", s)[0]
    return re.sub(r"[\s._-]", "", s)

def main():
    R = C.load_rpro3(DB)
    animals = R["animals"]
    by_norm = {}
    for a in animals:
        by_norm.setdefault(norm(a["name"]), []).append(a)
    mxp = rpro3_mxp.load_all(BACKUP)
    mxp_norm = {norm(k): (k, v) for k, v in mxp.items()}

    urllib.request.urlretrieve("http://localhost:5179/feedback", "fb.json")
    tickets = [t for t in json.load(open("fb.json", encoding="utf-8"))
               if not t.get("deletedAt") and t["status"] in ("NeedsInfo", "Open", "Answered")
               and t.get("gerbilId")]
    def gv(gid):
        try:
            return json.load(urllib.request.urlopen(f"http://localhost:5179/gerbils/{gid}", timeout=15))
        except Exception:
            return {}

    want = sys.argv[1:]
    for t in tickets:
        nm = t.get("entityName") or ""
        if want and not any(w.lower() in nm.lower() for w in want):
            continue
        g = gv(t["gerbilId"])
        dob = g.get("dateOfBirth")
        nn = norm(nm)
        cands = by_norm.get(nn, [])
        pick = None
        if dob:
            pick = next((a for a in cands if a["dob"] == dob), None)
        if not pick and len(cands) == 1:
            pick = cands[0]
        print(f"\n### [{t['status']}] {nm}  (live dob={dob})  ticket={t['id'][:8]}")
        print(f"    MSG: {(t.get('message') or '').strip()[:90]}")
        if pick:
            print(f"    rpro3: farbe={pick['farbe']} | fcode={pick['fcode']} | Vater={pick.get('father')} | Mutter={pick.get('mother')}")
        elif cands:
            print(f"    rpro3: {len(cands)} Namensvettern, keiner mit DOB {dob}: " +
                  "; ".join(f"{a['dob']}/{a['farbe']}" for a in cands[:5]))
        else:
            print("    rpro3: kein Treffer")
        if nn in mxp_norm:
            k, v = mxp_norm[nn]
            pr = v.get("parents", {})
            print(f"    .mxp[{k}]: V={pr.get('Vater',{}).get('name')} M={pr.get('Mutter',{}).get('name')} | Würfe={len(v.get('litters',[]))}")
    import os; os.remove("fb.json")

if __name__ == "__main__":
    main()
