#!/usr/bin/env python3
"""
Slice 2/5 — backfill WhatsApp outreach CRM into jarvis-memory.
Leads: DISTINCT peer_number, is_group=0, ORDER BY peer_number, LIMIT 92 OFFSET 92.
One fact per lead -> POST /remember. Reads MEMORY_API_KEY from ../.env (never printed).
"""
import json, os, sys, urllib.request, urllib.error

API = "https://jarvis-production-3e5f.up.railway.app/remember"
ENV = "/Users/ahmed/devFolder/Ultron/claude-voice/.env"
ACC = "966565625560"  # Ahmed's WA number (account) for every thread in this slice


def api_key():
    with open(ENV, encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line.startswith("MEMORY_API_KEY="):
                return line.split("=", 1)[1].strip().strip('"').strip("'")
    sys.exit("MEMORY_API_KEY not found in .env")


# Campaign entity labels
AIN = "AIN"                 # عين — AI-camera ops monitoring (tryain)
REVAL = "Reval"             # Reval agency (corporate games + social/content/design)
JOB = "Ahmed job search"    # Ahmed's personal job outreach (CV, أحمد الراجح)

# Each record: peer, name(None=>+peer), campaign entity, extra entity names[], importance, when(ISO), text
# text template: "WhatsApp lead +<peer> (<name>) — <campaign> cold outreach from Ahmed's WA +<acc>: <arc>. STOPPED AT: <stage>. <next>."
R = []


def add(peer, name, camp, extra, imp, when, text):
    R.append(dict(peer=peer, name=name, camp=camp, extra=extra, imp=imp, when=who(when), text=text))


def who(d):
    return d + "T12:00:00"


# ---- AIN (عين) — standard team pitch, no reply ----
ain_noreply = [
    ("149332103819482", "Moustafa", "2026-07-07"),
    ("149525025042641", "Mohammed", "2026-07-15"),
    ("155855857152142", "Maharaj", "2026-07-13"),
    ("160069186490429", "Maan", "2026-07-13"),
    ("160790875238575", "Mohammed", "2026-07-07"),
    ("162349864464619", "Abdulrazaq", "2026-07-15"),
    ("163191678091420", "Abdulrahman", "2026-07-13"),
    ("164295417573402", "Yousef", "2026-07-07"),
    ("166022598422559", "Abdullah", "2026-07-07"),
    ("167284781924436", "Mohammed", "2026-07-07"),
    ("168019170979904", "Azzam", "2026-07-15"),
    ("172919762223141", "Mohammed", "2026-07-07"),
    ("175385039925455", "Khalil", "2026-07-13"),
    ("176772331081744", "Mohannad", "2026-07-15"),
    ("177768830611701", "Abdullah", "2026-07-13"),
    ("178610644242452", "Abdulaziz", "2026-07-13"),
    ("179375198707956", "Sami", "2026-07-13"),
    ("180092491800665", "Turki", "2026-07-07"),
    ("180539034189898", "Abdulrahman", "2026-07-15"),
    ("181934898552870", "Essam", "2026-07-13"),
    ("183146096115743", "Salah", "2026-07-13"),
    ("184829823991927", "Badr", "2026-07-07"),
    ("190301528449069", "Mohammed", "2026-07-07"),
    ("192324390916179", "Yasser", "2026-07-07"),
    ("194884241764424", "Abdullah", "2026-07-13"),
    ("194987421655100", "Abdulrahman", "2026-07-13"),
    ("195738990563415", "Ibrahim", "2026-07-13"),
    ("198255824625740", "Waleed", "2026-07-07"),
]
for peer, name, d in ain_noreply:
    add(peer, name, AIN, [], 2, d,
        f"WhatsApp lead +{peer} ({name}) — AIN (عين) AI-camera ops-monitoring cold outreach from Ahmed's WA +{ACC}: "
        f"sent the standard عين pitch (turn existing CCTV into a real-time AI ops brain — cleanliness, queue/service time, "
        f"team productivity, instant alerts; free trial) on {d}; no reply. STOPPED AT: cold-sent, no reply. Next: follow up or drop.")

# 191018787971252 — AIN, Ahmed follow-up 'يا هلا', still no lead reply
add("191018787971252", "Abdullah", AIN, [], 2, "2026-07-08",
    f"WhatsApp lead +191018787971252 (Abdullah) — AIN (عين) AI-camera cold outreach from Ahmed's WA +{ACC}: "
    f"sent the عين pitch on 2026-07-07 and a 'يا هلا' nudge on 2026-07-08; no lead reply captured. "
    f"STOPPED AT: cold-sent + one nudge, no reply.")

# ---- AIN — personalized (أحمد من عين), named business, no reply ----
ain_biz_noreply = [
    ("155559521169468", "Walid Gobain", "FOUR LEAVES (الأوراق الأربعة)", "2026-07-07",
     "sent the personalized عين partner pitch for FOUR LEAVES on 2026-06-29 and re-sent the standard team pitch on 2026-07-07"),
    ("165652610441414", "Abdulaziz Aljubair", "Mayan", "2026-06-29",
     "sent the personalized عين partner pitch for Mayan (free install for feedback, 5-min call ask) on 2026-06-29"),
    ("174521751498908", "Walid Abdelaziz", "IGH Group", "2026-06-29",
     "sent the personalized عين partner pitch for IGH Group on 2026-06-29"),
    ("188562016329754", "Sultan Hassoun", "Anoud Food", "2026-07-07",
     "sent the personalized عين partner pitch for Anoud Food on 2026-06-29 and re-sent the team pitch on 2026-07-07"),
    ("199686031995034", "Abdullah Alkhuraiji", "Hospitality Time Co. Ltd.", "2026-06-29",
     "sent the personalized عين partner pitch for Hospitality Time Co. Ltd. on 2026-06-29"),
]
for peer, name, biz, d, arc in ain_biz_noreply:
    add(peer, name, AIN, [biz], 2, d,
        f"WhatsApp lead +{peer} ({name}, {biz}) — AIN (عين) AI-camera cold outreach from Ahmed's WA +{ACC}: "
        f"{arc}; no reply. STOPPED AT: cold-sent, no reply.")

# ---- AIN — interested / meeting / replied ----
add("14886406987972", "Mamdouh", AIN, [], 4, "2026-07-15",
    f"WhatsApp lead +14886406987972 (Mamdouh) — AIN (عين) AI-camera cold outreach from Ahmed's WA +{ACC}: "
    f"sent the عين pitch on 2026-07-15; Mamdouh replied same day 'شاركني ملف العرض' (share the offer file); Ahmed said ابشر and sent the proposal document. "
    f"STOPPED AT: interested — proposal file sent. Next: follow up on the offer.")

add("156401351585796", "Mohammed", AIN, [], 4, "2026-07-15",
    f"WhatsApp lead +156401351585796 (Mohammed) — AIN (عين) AI-camera cold outreach from Ahmed's WA +{ACC}: "
    f"sent the عين pitch on 2026-07-07; Mohammed replied 2026-07-15 'شاركنا الملف الله يعطيك العافية'; Ahmed sent the proposal document. "
    f"STOPPED AT: interested — proposal file sent. Next: follow up on the offer.")

add("176527551524969", "Younis Altewejri", AIN, ["The Rustic Bakery"], 4, "2026-06-29",
    f"WhatsApp lead +176527551524969 (Younis Altewejri, The Rustic Bakery) — AIN (عين) AI-camera cold outreach from Ahmed's WA +{ACC}: "
    f"sent the personalized عين partner pitch on 2026-06-29; Younis replied 'ما عندي مانع، يفضل نجتمع'; they agreed an online meeting for Sunday 3pm, "
    f"Ahmed gave his personal number 0544067114, offered to call, and sent a document same day. "
    f"STOPPED AT: MEETING agreed (Sunday 3pm, online). Next: hold the meeting / follow up.")

add("180745662369794", "Wisam Nasri", AIN, ["Baselat"], 4, "2026-07-12",
    f"WhatsApp lead +180745662369794 (Wisam Nasri, ops manager, Baselat — wisam@baselat.com / 0533610003) — AIN (عين) AI-camera outreach from Ahmed's WA +{ACC}: "
    f"REFERRED by 'أستاذ محمد' who gave Ahmed the number. Opened 2026-07-07, Wisam engaged, they scheduled a demo meeting for Thursday 3pm, "
    f"Ahmed emailed the invite; rescheduled to Sunday 3pm (Ahmed had a hospital appt); on 2026-07-12 both confirmed 'على موعدنا اليوم'. "
    f"STOPPED AT: MEETING confirmed (Sunday 3pm). Referral: came via Mr. Mohammed. Next: run the demo.")

add("188282944135253", "Faisal", AIN, [], 3, "2026-07-13",
    f"WhatsApp lead +188282944135253 (Faisal) — AIN (عين) AI-camera cold outreach from Ahmed's WA +{ACC}: "
    f"sent the عين pitch on 2026-07-13 then said 'تسلم ابشر' / 'ابشر برسلك' (implying Faisal reacted/asked positively; his message not captured). "
    f"STOPPED AT: replied — Ahmed promised to send the offer. Next: send the proposal + follow up.")

add("197486924837003", "Hisham", AIN, [], 3, "2026-07-13",
    f"WhatsApp lead +197486924837003 (Hisham) — AIN (عين) AI-camera cold outreach from Ahmed's WA +{ACC}: "
    f"sent the عين pitch on 2026-07-13; Hisham replied with a voice note (not transcribed); Ahmed said ابشر and sent the proposal document. "
    f"STOPPED AT: replied via voice — proposal sent. Next: transcribe the voice note + follow up.")

# ---- Reval — corporate games / team-building (put employees in a video game), no reply ----
reval_games_noreply = [
    ("149748480757767", "Sultana", "2026-06-19", "short"),
    ("149924607963199", "Abdulrahman", "2026-06-19", "short"),
    ("15247318511787", "Rashed", "2026-06-17", "long"),
    ("155838710845538", "Asma", "2026-06-19", "short"),
    ("161327762923635", "Afnan", "2026-06-17", "long"),
    ("166447263285475", "Amal", "2026-06-17", "long"),
    ("168066885353684", "Firas", "2026-06-19", "short"),
    ("176128119590924", "Arif", "2026-06-17", "short"),
    ("178322831073451", "Azad", "2026-06-17", "short"),
    ("181028610146484", "Hamam", "2026-06-17", "long"),
    ("181041478291480", "Waad", "2026-06-19", "short"),
    ("18206483812389", "Mesfer", "2026-06-17", "long"),
    ("190258645844195", "Mohammed", "2026-06-17", "long"),
    ("195189117325389", "Abdulhadi", "2026-06-17", "long"),
    ("1954294005979", "Ghaida", "2026-06-19", "short"),
    ("196035326529745", "Ali", "2026-06-17", "short"),
    ("196490609836235", "Fatima", "2026-06-19", "short"),
    ("197216341876946", "Darin", "2026-06-19", "short"),
    ("198590731419692", "Esraa", "2026-06-19", "short"),
    ("198835712323633", "Ibrahim", "2026-06-17", "long"),
]
for peer, name, d, kind in reval_games_noreply:
    add(peer, name, REVAL, [], 2, d,
        f"WhatsApp lead +{peer} ({name}) — Reval corporate-games / team-building cold outreach from Ahmed's WA +{ACC}: "
        f"sent the 'put your employees inside a video game' pitch (custom fighting/football games, employee becomes a character, "
        f"for World-Cup/employee fun-day events; Reval did this for Al-Rugaib Furniture HR) on {d}; no reply. "
        f"STOPPED AT: cold-sent, no reply.")

# Reval games — replied
add("152596010516546", "Layan", REVAL, [], 4, "2026-06-29",
    f"WhatsApp lead +152596010516546 (Layan) — Reval corporate-games cold outreach from Ahmed's WA +{ACC}: "
    f"sent the employees-in-a-game pitch on 2026-06-19; Layan replied 'ايه ارسل اشوف'; Ahmed sent a portfolio doc + an Al-Rugaib Furniture example image, "
    f"then followed up 2026-06-29 offering a tailored World-Cup experience proposal (no further reply). "
    f"STOPPED AT: interested — portfolio sent, awaiting reply. Next: follow up on the World-Cup offer.")

add("183532559290395", "Maher", REVAL, [], 3, "2026-07-15",
    f"WhatsApp lead +183532559290395 (Maher) — Reval corporate-games cold outreach from Ahmed's WA +{ACC}: "
    f"sent the employees-in-a-game pitch on 2026-06-19; Maher pinged back 2026-07-14; Ahmed said ابشر and sent a Google-Drive portfolio link 2026-07-15. "
    f"STOPPED AT: replied — portfolio link sent. Next: follow up.")

# ---- Reval — social-media / content-marketing ('نحول المحتوى إلى عملاء'), no reply ----
reval_content_noreply = [
    ("152278669484170", None, "2026-04-07"),
    ("162719265231070", None, "2026-04-07"),
    ("16532151238660", None, "2026-04-07"),
    ("170158584807569", None, "2026-04-07"),
]
for peer, name, d in reval_content_noreply:
    disp = name or f"+{peer}"
    add(peer, name, REVAL, [], 2, d,
        f"WhatsApp lead +{peer} ({disp}) — Reval social-media/content-marketing cold outreach from Ahmed's WA +{ACC}: "
        f"sent the 'ريفال — نحول المحتوى إلى عملاء' cafe/restaurant content+ads pitch offering a free growth plan on {d}; no reply. "
        f"STOPPED AT: cold-sent, no reply.")

# Reval content — 'Reval Agency' doc variant, no reply
reval_agency_noreply = [
    ("154116881940568", "2026-07-03"),
    ("174410484953124", "2026-07-03"),
    ("180191779397718", "2026-07-03"),
]
for peer, d in reval_agency_noreply:
    add(peer, None, REVAL, [], 2, d,
        f"WhatsApp lead +{peer} (+{peer}) — Reval Agency social-media/content cold outreach from Ahmed's WA +{ACC}: "
        f"sent the Reval Agency doc pitch (social-media management, design & content for cafes/restaurants, limited-time package discount) on {d}; no reply. "
        f"STOPPED AT: cold-sent, no reply.")

# Reval — free-design offer variant, no reply
reval_design_noreply = [
    ("155804518887599", "2026-04-16", "single"),
    ("17287897682084", "2026-04-16", "single"),
    ("171742991499360", "2026-04-16", "afterpitch"),
]
for peer, d, kind in reval_design_noreply:
    extra = (" (after an earlier 2026-04-07 'نحول المحتوى إلى عملاء' pitch)" if kind == "afterpitch" else "")
    add(peer, None, REVAL, [], 2, d,
        f"WhatsApp lead +{peer} (+{peer}) — Reval free-design/content cold outreach from Ahmed's WA +{ACC}: "
        f"offered a free design on one of their products (work together if they like it){extra} on {d}; no reply. "
        f"STOPPED AT: cold-sent, no reply.")

# Reval content — auto-reply from a business bot only (no human engagement)
reval_autoreply = [
    ("154533309206668", "Ahla Hala", "2026-04-05", "restaurant chain"),
    ("156307214569495", "Mawashi", "2026-04-15", "meat retailer (mawashico.com)"),
    ("179118037561505", "Ritz-Carlton Riyadh", "2026-04-16", "hotel restaurant"),
    ("198385042780257", "Q Lounge", "2026-04-07", "lounge"),
]
for peer, biz, d, kind in reval_autoreply:
    add(peer, biz, REVAL, [], 2, d,
        f"WhatsApp lead +{peer} ({biz}, {kind}) — Reval content/design cold outreach from Ahmed's WA +{ACC}: "
        f"sent the Reval pitch on {d}; only an automated business auto-reply came back (no human engagement). "
        f"STOPPED AT: cold-sent, auto-reply only.")

# Reval content — replied / interested
add("16510022074489", "Zony", REVAL, [], 3, "2026-04-05",
    f"WhatsApp lead +16510022074489 (Zony team) — Reval social-media/content cold outreach from Ahmed's WA +{ACC}: "
    f"sent the 'نحول المحتوى إلى عملاء' pitch on 2026-04-05; Zony replied politely 'حياك الله تفضلوا'; Ahmed thanked them (no substantive follow-through). "
    f"STOPPED AT: replied (polite). Next: re-engage with the free plan.")

add("168775840190591", None, REVAL, [], 4, "2026-04-08",
    f"WhatsApp lead +168775840190591 (+168775840190591) — Reval content cold outreach from Ahmed's WA +{ACC}: "
    f"sent the 'نحول المحتوى إلى عملاء' pitch on 2026-04-07; lead replied 'ارسل' (send it) on 2026-04-08. "
    f"STOPPED AT: interested — asked to receive the proposal. Next: send the free growth plan.")

add("180208690851867", None, REVAL, [], 4, "2026-04-16",
    f"WhatsApp lead +180208690851867 (+180208690851867) — Reval content cold outreach from Ahmed's WA +{ACC}: "
    f"sent the content pitch on 2026-04-07; lead replied 'نعم' (yes); Ahmed followed up 2026-04-16 asking for a product photo to make a free sample post (no further reply). "
    f"STOPPED AT: interested — agreed, awaiting a product photo. Next: chase the photo + send the free post.")

# 159210847342669 — Reval content, real conversation (Khafji productive-family), saw portfolio + prices
add("159210847342669", None, REVAL, [], 4, "2026-04-16",
    f"WhatsApp lead +159210847342669 (+159210847342669, a home-based 'أسرة منتجة' in Khafji, Eastern Province) — Reval content/photography cold outreach from Ahmed's WA +{ACC}: "
    f"sent the content pitch on 2026-04-07; lead engaged, asked to see the work and location (Reval based in Dhahran/Al-Khobar); "
    f"Ahmed sent portfolio images and the full package price list (Starter 1,500 / Growth 3,000 / Premium 8,000 / Launch 4,500 SAR), "
    f"then followed up 2026-04-16 offering a free sample design (no further reply). "
    f"STOPPED AT: interested — saw portfolio + prices, went quiet. Next: follow up with the free-design hook.")

# 177769250037805 — Reval content 'فريق كبس', no reply
add("177769250037805", "Kabs", REVAL, [], 2, "2026-04-05",
    f"WhatsApp lead +177769250037805 (Kabs team) — Reval social-media/content cold outreach from Ahmed's WA +{ACC}: "
    f"sent the 'نحول المحتوى إلى عملاء' pitch on 2026-04-05; no reply. STOPPED AT: cold-sent, no reply.")

# 181295015559262 — declined (cold msg body blank; 2026-04-07 Reval-content batch)
add("181295015559262", None, REVAL, [], 2, "2026-04-07",
    f"WhatsApp lead +181295015559262 (+181295015559262) — Reval content cold outreach from Ahmed's WA +{ACC}: "
    f"opened 2026-04-07 (within the Reval content blast; the cold message body wasn't captured); lead replied 'لا شكرا' (no thanks); Ahmed closed politely. "
    f"STOPPED AT: DECLINED. Next: none — do not re-contact.")

# ---- Ahmed's personal job outreach (CV, أحمد الراجح) — all cold-sent, no reply ----
job_noreply = [
    ("154627513266353", "Arwa", "2026-07-02"),
    ("155482312454375", "Mohammed", "2026-07-02"),
    ("160807937654819", "Eyad", "2026-07-02"),
    ("161267599806604", "Abdulrahman", "2026-07-02"),
    ("162775150117112", "Faisal", "2026-07-01"),
    ("168302638817480", "Saud", "2026-07-01"),
    ("17188610154653", "Fadi", "2026-07-02"),
    ("187453864452166", "Fuaad", "2026-07-01"),
    ("199866370273320", "Ahmed", "2026-07-02"),
]
for peer, name, d in job_noreply:
    add(peer, name, JOB, [], 2, d,
        f"WhatsApp lead +{peer} ({name}) — Ahmed's personal job outreach (أحمد الراجح, CV attached) to a hiring/talent contact from his WA +{ACC}: "
        f"pitched 'give me a real technical/ops problem and I'll build you a working product free, no obligation — then let's talk about a role' "
        f"and sent his CV on {d}; no reply. STOPPED AT: cold-sent, no reply. Next: follow up on the job pitch.")


def post(rec, token):
    ents = [{"name": rec["name"] or f"+{rec['peer']}"}, {"name": rec["camp"]}]
    for e in rec["extra"]:
        ents.append({"name": e})
    body = {
        "text": rec["text"],
        "kind": "fact",
        "when": rec["when"],
        "importance": rec["imp"],
        "confidence": 0.8,
        "source": "wa-backfill",
        "group": "ahmed",
        "entities": ents,
    }
    data = json.dumps(body).encode("utf-8")
    req = urllib.request.Request(API, data=data, method="POST")
    req.add_header("Content-Type", "application/json")
    req.add_header("Authorization", f"Bearer {token}")
    try:
        with urllib.request.urlopen(req, timeout=45) as r:
            return r.status, r.read(200).decode("utf-8", "replace")
    except urllib.error.HTTPError as e:
        return e.code, e.read(300).decode("utf-8", "replace")
    except Exception as e:
        return 0, str(e)


def main():
    token = api_key()
    # sanity: no duplicate peers
    peers = [r["peer"] for r in R]
    assert len(peers) == len(set(peers)), "duplicate peer in records"
    ok = fail = 0
    for rec in R:
        st, resp = post(rec, token)
        if st in (200, 201):
            ok += 1
        else:
            fail += 1
            print(f"FAIL {rec['peer']} status={st} resp={resp[:160]}")
    print(f"\nRECORDS={len(R)} WRITTEN={ok} FAILED={fail}")


if __name__ == "__main__":
    main()
