#!/usr/bin/env python3
"""Re-generate Claude suggestions via claude CLI.
Learns keith's style directly from his real messages in the CSV."""

import csv, subprocess, os, random
from pathlib import Path
from datetime import datetime, timedelta
from concurrent.futures import ThreadPoolExecutor, as_completed

DM_CSV = Path(__file__).parent / "follow_up_FULL.csv"
CUTOFF = datetime.now() - timedelta(days=60)
WORKERS = 1
ENV = {k: v for k, v in os.environ.items() if k != "ANTHROPIC_API_KEY"}

def parse_date(d):
    try:
        return datetime.strptime(d, "%Y-%m-%d %H:%M")
    except:
        return datetime.min

rows = []
with open(DM_CSV, encoding="utf-8") as f:
    rows = list(csv.DictReader(f))
fieldnames = list(rows[0].keys())

# collect keith's real messages as style examples
keith_examples = []
for r in rows:
    msg = r["keith_last_msg"].strip()
    if msg and not msg.startswith("[") and 30 < len(msg) < 280:
        keith_examples.append(msg)

def get_suggestion(row):
    sample = random.sample(keith_examples, min(10, len(keith_examples)))
    examples = "\n".join(f"- {m}" for m in sample)

    prompt = f"""you are writing instagram DMs as keith motes (@shakingmedicine).

here are real messages keith has sent — learn his exact tone, style, and phrasing from these:
{examples}

now write his next message in this conversation.
conversation with {row['display_name']}:
{row['conversation_summary'].replace(' | ', chr(10))[-1500:]}

situation: {row['follow_up_type']} — {'they replied and keith hasn\'t responded yet' if row['follow_up_type'] == 'NEEDS_REPLY' else 'keith sent last, no reply came — re-engage naturally'}

write keith's message only. nothing else."""

    try:
        r = subprocess.run(
            ["claude", "-p", prompt],
            capture_output=True, text=True, timeout=45, env=ENV
        )
        text = r.stdout.strip()
        return text if text and r.returncode == 0 else f"[failed: {r.stderr[:100]}]"
    except Exception as e:
        return f"[failed: {e}]"

# only process NEEDS_REPLY + recent BUMP_UP
to_process = []
for i, row in enumerate(rows):
    if row.get("suggested_reply") and not row["suggested_reply"].startswith("["):
        continue
    if row["follow_up_type"] == "NEEDS_REPLY" or parse_date(row["last_msg_date"]) >= CUTOFF:
        to_process.append((i, row))

print(f"generating {len(to_process)} suggestions (learning from {len(keith_examples)} real keith messages)\n")

done = 0
errors = 0

with ThreadPoolExecutor(max_workers=WORKERS) as ex:
    futures = {ex.submit(get_suggestion, row): (i, row) for i, row in to_process}
    for future in as_completed(futures):
        i, row = futures[future]
        suggestion = future.result()
        rows[i]["suggested_reply"] = suggestion
        if suggestion.startswith("[failed"):
            errors += 1
            print(f"  error: {row['handle']}")
        else:
            done += 1
            print(f"  [{done}/{len(to_process)}] {row['handle']} ✓")

with open(DM_CSV, "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(rows)

print(f"\ndone: {done} suggestions, {errors} errors")
