#!/usr/bin/env python3
"""
Keith Instagram DM Scanner
Reads all DM threads, checks who sent last + when, outputs CSV for follow-up.
"""

import csv
import json
import os
import time
from datetime import datetime
from pathlib import Path

from instagrapi import Client

# ── Config ─────────────────────────────────────────────────────────────────
USERNAME = os.environ.get("IG_USERNAME", "shakingmedicine")
PASSWORD = os.environ.get("IG_PASSWORD", "")
SESSION_FILE = Path(__file__).parent / "session.json"
OUTPUT_FILE = Path(__file__).parent / "follow_up_scan.csv"
MAX_THREADS = 500  # how many threads to scan

# ── Auth via Chrome session cookie ─────────────────────────────────────────
import rookiepy
from urllib.parse import unquote

cl = Client()
cl.delay_range = [1, 3]

print("Extracting Instagram session from Chrome...")
cookies = rookiepy.chrome(domains=["instagram.com"])
cookie_dict = {c["name"]: c["value"] for c in cookies}

session_id = unquote(cookie_dict["sessionid"])
print(f"Session ID found, logging in...")
cl.login_by_sessionid(session_id)
cl.dump_settings(SESSION_FILE)
print(f"Logged in as: {cl.account_info().username}")

# ── Scan threads ────────────────────────────────────────────────────────────
print(f"\nFetching up to {MAX_THREADS} threads...")
threads = cl.direct_threads(amount=MAX_THREADS)
print(f"Found {len(threads)} threads.")

results = []

for i, thread in enumerate(threads):
    try:
        users = [u for u in thread.users if u.username != USERNAME]
        if not users:
            continue

        other = users[0]
        handle = other.username
        display_name = other.full_name or handle

        # last message
        if not thread.messages:
            continue

        last_msg = thread.messages[0]
        last_sender_id = str(last_msg.user_id)
        my_id = str(cl.user_id)

        keith_sent_last = (last_sender_id == my_id)
        last_sender = "KEITH" if keith_sent_last else "OTHER"

        msg_text = ""
        if hasattr(last_msg, "text") and last_msg.text:
            msg_text = last_msg.text[:200]
        elif hasattr(last_msg, "item_type"):
            msg_text = f"[{last_msg.item_type}]"

        ts = last_msg.timestamp
        if hasattr(ts, "strftime"):
            date_str = ts.strftime("%Y-%m-%d %H:%M")
        else:
            date_str = str(ts)

        follow_up_type = "BUMP_UP" if keith_sent_last else "NEEDS_REPLY"

        results.append({
            "handle": f"@{handle}",
            "display_name": display_name,
            "last_msg_date": date_str,
            "last_sender": last_sender,
            "last_msg_text": msg_text,
            "follow_up_type": follow_up_type,
            "thread_id": thread.id,
        })

        if (i + 1) % 20 == 0:
            print(f"  {i+1}/{len(threads)} scanned...")

        time.sleep(0.5)

    except Exception as e:
        print(f"  Error on thread {i}: {e}")
        continue

# ── Write CSV ────────────────────────────────────────────────────────────────
bump_up = [r for r in results if r["follow_up_type"] == "BUMP_UP"]
needs_reply = [r for r in results if r["follow_up_type"] == "NEEDS_REPLY"]

print(f"\nResults:")
print(f"  BUMP_UP (Keith sent last, no reply): {len(bump_up)}")
print(f"  NEEDS_REPLY (other replied, Keith hasn't):  {len(needs_reply)}")

fieldnames = ["handle", "display_name", "last_msg_date", "last_sender", "last_msg_text", "follow_up_type", "thread_id"]

with open(OUTPUT_FILE, "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    # BUMP_UP first (oldest first), then NEEDS_REPLY
    for r in sorted(bump_up, key=lambda x: x["last_msg_date"]):
        writer.writerow(r)
    for r in sorted(needs_reply, key=lambda x: x["last_msg_date"]):
        writer.writerow(r)

print(f"\nSaved to: {OUTPUT_FILE}")
print("Done.")
