#!/usr/bin/env python3
"""X Account Monitor — Scan Chunk 1 (accounts 1-22)"""
import urllib.request, json, time, os, sys
from datetime import datetime, timezone, timedelta

API_KEY = "get-x-api-6157f8edb420c3d5e50e062287389aa55635cd7c9630c81f"
BASE_URL = "https://api.getxapi.com"
RESULTS_FILE = "/home/kiro/trend-engine/trends/x/account-monitor/scan_results_2026-06-18_CHUNK1.json"

BIO_INFO = {
    "runwayml": "Runway AI — professional AI filmmaking (~260K)",
    "CuriousRefuge": "Curious Refuge — home for AI filmmakers",
    "nofilmschool": "No Film School — filmmaking news (~241.7K)",
    "venturetwins": "Justine Moore — a16z partner AI video (~149.5K)",
    "Kling_ai": "Kling AI — AI video generation (~130K)",
    "paultrillo": "Paul Trillo — LA director/artist (~15K)",
    "c_valenzuelab": "Cristóbal Valenzuela — Runway CEO (~42.7K)",
    "CorridorDigital": "Corridor Digital — VFX/filmmaking (15M+ YouTube)",
    "karenxcheng": "Karen X. Cheng — Director, brand AI video (~58K)",
    "higgsfield": "Higgsfield AI — multi-model platform (~63K)",
    "pika_labs": "Pika — AI video for social creators (~143K)",
    "EHuanglu": "el.cine / Elsa Huang — Film director, AI consultant (~128K)",
}

HANDLES = [
    "runwayml", "CuriousRefuge", "nofilmschool", "venturetwins", "Kling_ai",
    "paultrillo", "c_valenzuelab", "CorridorDigital", "karenxcheng", "higgsfield",
    "pika_labs", "EHuanglu", "azed_ai", "JeffSynthesized", "ai_filmmaker",
    "visiblemaker", "Magiermogul", "WuxiaRocks", "JiamingSuen", "moonvalley",
    "higgsfield_ai", "Chandan_Perla",
]

CUTOFF = datetime(2026, 6, 15, 0, 0, 0, tzinfo=timezone.utc)
date_str = "2026-06-18"

def parse_date(created_at):
    if not created_at:
        return None
    try:
        return datetime.strptime(created_at, "%a %b %d %H:%M:%S %z %Y")
    except:
        return None

def fetch_tweets(handle):
    url = f"{BASE_URL}/twitter/user/tweets?userName={handle}&count=5"
    req = urllib.request.Request(url, headers={"Authorization": f"Bearer {API_KEY}"})
    try:
        with urllib.request.urlopen(req, timeout=30) as resp:
            body = resp.read().decode("utf-8", errors="replace")
        data = json.loads(body, strict=False)
        if isinstance(data, dict) and "tweets" in data:
            return data["tweets"]
        elif isinstance(data, list):
            return data
        else:
            return []
    except Exception as e:
        print(f"  ERROR for @{handle}: {e}", file=sys.stderr)
        return None

def process_tweets(handle, raw_tweets):
    """Apply date filter and engagement thresholds, compute scores."""
    if raw_tweets is None:
        return None, [], []
    
    # Filter by date (3-day cutoff)
    recent = []
    for t in raw_tweets:
        dt = parse_date(t.get("createdAt", ""))
        if dt and dt >= CUTOFF:
            recent.append(t)
    
    # Extract engagement numbers
    qualifying = []
    for t in recent:
        likes = int(t.get("likeCount", 0) or 0)
        retweets = int(t.get("retweetCount", 0) or 0)
        replies = int(t.get("replyCount", 0) or 0)
        views = int(t.get("viewCount", 0) or 0)
        bookmarks = int(t.get("bookmarkCount", 0) or 0)
        
        # Engagement thresholds
        if likes >= 50 or retweets >= 10 or views >= 1000:
            score = likes + (retweets * 2) + replies + (views // 100)
            tweet_id = t.get("id", t.get("tweetId", ""))
            text = t.get("text", "")
            if len(text) > 120:
                text = text[:117] + "..."
            text = text.replace("\n", " ").replace("\r", " ")
            
            qualifying.append({
                "id": str(tweet_id),
                "text": text,
                "date": parse_date(t.get("createdAt", "")).strftime("%Y-%m-%d") if parse_date(t.get("createdAt", "")) else "",
                "likes": likes,
                "retweets": retweets,
                "replies": replies,
                "views": views,
                "bookmarks": bookmarks,
                "score": score,
            })
    
    qualifying.sort(key=lambda x: x["score"], reverse=True)
    return recent, qualifying

# Load existing results (resume support)
all_results = {"accounts": [], "errors": [], "scan_date": f"{date_str} 06:00 UTC"}
done_handles = set()
if os.path.exists(RESULTS_FILE):
    try:
        with open(RESULTS_FILE) as f:
            existing = json.load(f)
            all_results = existing
            done_handles = set(a["handle"] for a in all_results.get("accounts", []))
        print(f"Resuming from {len(done_handles)} already-scanned accounts")
    except:
        pass

print(f"Chunk 1: Scanning {len(HANDLES)} accounts...")
print(f"Cutoff date: {CUTOFF.strftime('%Y-%m-%d')} UTC")

for i, handle in enumerate(HANDLES):
    if handle in done_handles:
        print(f"  [{i+1}/{len(HANDLES)}] @{handle} — SKIP (already done)")
        continue
    
    print(f"  [{i+1}/{len(HANDLES)}] @{handle}...", end=" ", flush=True)
    raw = fetch_tweets(handle)
    
    if raw is None:
        all_results["errors"].append({"handle": handle, "error": "API request failed"})
        print("ERROR (API failure)")
    elif len(raw) == 0:
        all_results["accounts"].append({
            "handle": handle,
            "bio": BIO_INFO.get(handle, ""),
            "total_fetched": 0,
            "recent_count": 0,
            "qualifying_count": 0,
            "tweets": [],
        })
        print("0 tweets")
    else:
        recent, qualifying = process_tweets(handle, raw)
        all_results["accounts"].append({
            "handle": handle,
            "bio": BIO_INFO.get(handle, ""),
            "total_fetched": len(raw),
            "recent_count": len(recent),
            "qualifying_count": len(qualifying),
            "tweets": qualifying,
        })
        if len(qualifying) > 0:
            top = qualifying[0]
            print(f"{len(raw)} fetched, {len(recent)} recent, {len(qualifying)} qual (top: {top['score']}pts, {top['likes']}L/{top['retweets']}RT/{top['views']}V)")
        else:
            print(f"{len(raw)} fetched, {len(recent)} recent, 0 qualifying")
    
    # Incremental save
    with open(RESULTS_FILE + ".tmp", "w") as f:
        json.dump(all_results, f, indent=2)
    
    time.sleep(1)

# Final save
os.rename(RESULTS_FILE + ".tmp", RESULTS_FILE)
print(f"\nChunk 1 complete. {len(all_results['accounts'])} accounts, {len(all_results['errors'])} errors.")
