#!/usr/bin/env python3
"""Generate one-line 'focus hint' for NEEDS_REPLY rows.

Tells keith what to address in his reply. Read by build_audit.py and rendered
in the REPLY tab as 'focus on: ...'. Run after auto_update.py / re_suggest.py.
"""
import csv, subprocess, os, shutil, sys
from pathlib import Path
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor, as_completed

BASE = Path(__file__).parent if Path(__file__).parent.name == "keith-dm-scanner" else Path("/Users/daichi/keith-dm-scanner")
DM_CSV = BASE / "follow_up_FULL.csv"
CLAUDE_BIN = "/Users/daichi/.local/bin/claude"
ENV = {k: v for k, v in os.environ.items() if k != "ANTHROPIC_API_KEY"}
WORKERS = 2

PROMPT_HEAD = """read this instagram DM conversation. in ONE short sentence (max 18 words), tell keith what specific points he should address in his next reply. focus on the prospect's actual question or signal. start with a verb. no preamble, no quotes, no labels. output the sentence only.

examples of good outputs:
- answer her question about retreat pricing and offer the skool community as alternative
- engage on his TRE practice and ask what shifted in the last few weeks
- acknowledge the breakup and ask gently how she's caring for her nervous system right now
- mirror her excitement about Bali, then ask what brought her to shaking medicine

conversation:
"""

def get_focus(row):
    summary = row["conversation_summary"].replace(" | ", "\n")[-1500:]
    prompt = PROMPT_HEAD + summary
    try:
        r = subprocess.run([CLAUDE_BIN, "-p", prompt],
                           capture_output=True, text=True, timeout=60, env=ENV)
        text = r.stdout.strip().split("\n")[0].strip()
        # strip surrounding quotes if any
        if text.startswith(("'", '"')) and text.endswith(("'", '"')):
            text = text[1:-1].strip()
        if r.returncode == 0 and text:
            return text
        return ""
    except Exception:
        return ""

# load
with open(DM_CSV, encoding="utf-8") as f:
    reader = csv.DictReader(f)
    fields = reader.fieldnames
    rows = list(reader)
print(f"loaded {len(rows)} rows", flush=True)

# add focus_hint column if missing
if "focus_hint" not in fields:
    fields = list(fields) + ["focus_hint"]
    print("added focus_hint column", flush=True)
for r in rows:
    r.setdefault("focus_hint", "")

# pick targets: NEEDS_REPLY rows. Regenerate every run (cheap, ~30-50 rows).
targets = [(i, r) for i, r in enumerate(rows) if r.get("follow_up_type") == "NEEDS_REPLY"]
print(f"targets: {len(targets)} NEEDS_REPLY rows", flush=True)
if not targets:
    print("nothing to do", flush=True)
    sys.exit(0)

# backup
ts = datetime.now().strftime("%Y%m%d-%H%M%S")
bak = DM_CSV.with_name(f"follow_up_FULL.csv.bak-{ts}-prefocus")
shutil.copy2(DM_CSV, bak)
print(f"backup: {bak.name}", flush=True)

# parallel
done = 0
with ThreadPoolExecutor(max_workers=WORKERS) as ex:
    futures = {ex.submit(get_focus, r): (i, r) for i, r in targets}
    for fut in as_completed(futures):
        i, r = futures[fut]
        hint = fut.result()
        rows[i]["focus_hint"] = hint
        done += 1
        if done % 10 == 0 or done == len(targets):
            short = (hint or "[empty]")[:70].replace("\n", " ")
            print(f"  [{done}/{len(targets)}] {r['handle']} → {short}", flush=True)
            # incremental write
            with open(DM_CSV, "w", newline="", encoding="utf-8") as f:
                w = csv.DictWriter(f, fieldnames=fields)
                w.writeheader(); w.writerows(rows)

# final write
with open(DM_CSV, "w", newline="", encoding="utf-8") as f:
    w = csv.DictWriter(f, fieldnames=fields)
    w.writeheader(); w.writerows(rows)
print(f"\ndone. focus_hint generated for {done} rows.", flush=True)
