#!/usr/bin/env python3
"""Chunk 1: Scan first 22 accounts — 2026-06-15"""
import json, os, sys, time, urllib.request, urllib.error
from datetime import datetime, timezone

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-15.json"
CUTOFF = datetime(2026, 6, 12, 0, 0, 0, tzinfo=timezone.utc)

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",
]

IRRELEVANT_HANDLES = {
    "CINEMA505", "TheAIColony", "GoogleLabs", "GoogleAI", "Ai_Vaidehi",
    "AI_with_jasmin", "CharaspowerAI", "AIBuzzNews", "AlexStudio44",
    "FaithJaiye2187", "KammelaBala", "MyStageAI",
}

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)
    except Exception as e:
        return None, str(e)

    if isinstance(data, dict):
        tweets = data.get("tweets", data.get("data", []))
    else:
        tweets = data if isinstance(data, list) else []

    return tweets, None

def process_tweets(handle, raw_tweets):
    processed = []
    for t in raw_tweets:
        if not isinstance(t, dict):
            continue
        # Skip RTs
        text = t.get("text", "")
        is_rt = text.startswith("RT @")

        createdAt = t.get("createdAt", "")
        dt = parse_date(createdAt)
        date_str = dt.strftime("%Y-%m-%d") if dt else ""

        likes = t.get("likeCount", 0) or 0
        retweets = t.get("retweetCount", 0) or 0
        replies = t.get("replyCount", 0) or 0
        views = t.get("viewCount", 0) or 0
        bookmarks = t.get("bookmarkCount", 0) or 0

        score = likes + (retweets * 2) + replies + (views / 100)

        tweet_id = t.get("id", "") or t.get("tweetId", "") or t.get("restId", "")

        processed.append({
            "id": str(tweet_id),
            "text": text[:200],
            "date": date_str,
            "createdAt": createdAt,
            "likes": likes,
            "retweets": retweets,
            "replies": replies,
            "views": views,
            "bookmarks": bookmarks,
            "score": round(score, 1),
            "is_rt": is_rt,
        })

    # Filter by date cutoff (past 3 days)
    recent = [t for t in processed if t["date"] and t["date"] >= "2026-06-12"]

    # Apply engagement thresholds
    qualifying = [t for t in recent if
        t["likes"] >= 50 or t["retweets"] >= 10 or t["views"] >= 1000]

    qualifying.sort(key=lambda x: x["score"], reverse=True)

    is_irrelevant = handle in IRRELEVANT_HANDLES

    return {
        "handle": handle,
        "tweets": qualifying,
        "recent_count": len(recent),
        "qualifying_count": len(qualifying),
        "is_irrelevant": is_irrelevant,
    }

# Load existing results (resume support)
all_results = {"accounts": [], "errors": [], "scan_date": "2026-06-15 06:00 UTC"}
if os.path.exists(RESULTS_FILE):
    try:
        with open(RESULTS_FILE) as f:
            all_results = json.load(f)
    except:
        pass

done_handles = set(a["handle"] for a in all_results.get("accounts", []))
print(f"Resuming: {len(done_handles)} already scanned, {len(HANDLES) - len(done_handles)} remaining in chunk 1")

for i, handle in enumerate(HANDLES):
    if handle in done_handles:
        print(f"  SKIP {handle} (already scanned)")
        continue

    print(f"  [{i+1}/{len(HANDLES)}] Fetching @{handle}...", end=" ", flush=True)
    raw_tweets, error = fetch_tweets(handle)

    if error:
        print(f"ERROR: {error}")
        all_results.setdefault("errors", []).append(f"@{handle}: {error}")
    else:
        account_data = process_tweets(handle, raw_tweets)
        if isinstance(raw_tweets, list):
            total_fetched = len(raw_tweets)
        else:
            total_fetched = 0
        print(f"OK ({total_fetched} fetched, {account_data['recent_count']} recent, {account_data['qualifying_count']} qualifying)")
        all_results["accounts"].append(account_data)

    # Incremental save
    with open(RESULTS_FILE + ".tmp", "w") as f:
        json.dump(all_results, f, indent=2)

    time.sleep(1.2)

# Rename to final
os.rename(RESULTS_FILE + ".tmp", RESULTS_FILE)

total = len(all_results["accounts"])
qual = sum(1 for a in all_results["accounts"] if a["qualifying_count"] > 0)
errs = len(all_results.get("errors", []))
print(f"\nChunk 1 complete: {total} accounts, {qual} with qualifying tweets, {errs} errors")
print(f"Saved to {RESULTS_FILE}")
