#!/usr/bin/env python3
"""X Account Monitor — Scan Chunk 2 (accounts 23-44)"""
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_CHUNK2.json"

HANDLES = [
    "AITOPIAai", "FaithJaiye2187", "KammelaBala", "MyStageAI",
    "AI_Video_Dumps", "ChrisLaubAI", "GoogleLabs", "TheAIColony",
    "cladlabs", "AIBuzzNews", "AlexStudio44", "DonutAI", "GoogleAI",
    "AI_with_jasmin", "CharaspowerAI", "Ai_Vaidehi", "CINEMA505",
    "AIFrontliner", "AIGuideHQ", "AIWarper", "AITECHio", "4aibsc",
]

BIO_INFO = {
    "AITOPIAai": "AI platform — Grok Imagine Video integrations",
    "ChrisLaubAI": "RT-only account — FILTERED, zero AI filmmaking content",
    "AIFrontliner": "AI news aggregator — ChatGPT/Claude prompts, Seedance mentions",
    "AIWarper": "AI creator — Seedance 2.0 prompts, ComfyUI workflows",
    "AITECHio": "AI/crypto hybrid — ACN token, AI infrastructure",
    "DonutAI": "AI tool ecosystem — small but on-topic",
}

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

    recent = []
    for t in raw_tweets:
        dt = parse_date(t.get("createdAt", ""))
        if dt and dt >= CUTOFF:
            recent.append(t)

    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)

        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", " ")
            pt = parse_date(t.get("createdAt", ""))
            dt_str = pt.strftime("%Y-%m-%d") if pt else ""

            qualifying.append({
                "id": str(tweet_id),
                "text": text,
                "date": dt_str,
                "likes": likes,
                "retweets": retweets,
                "replies": replies,
                "views": views,
                "bookmarks": bookmarks,
                "score": score,
            })

    qualifying.sort(key=lambda x: x["score"], reverse=True)
    return 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 2: 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,
            "qualifying_count": 0,
            "tweets": [],
        })
        print("0 tweets")
    else:
        qualifying = process_tweets(handle, raw)
        all_results["accounts"].append({
            "handle": handle,
            "bio": BIO_INFO.get(handle, ""),
            "total_fetched": len(raw),
            "qualifying_count": len(qualifying),
            "tweets": qualifying,
        })
        if len(qualifying) > 0:
            top = qualifying[0]
            print(f"{len(raw)} fetched, {len(qualifying)} qual (top: {top['score']}pts, {top['likes']}L/{top['retweets']}RT/{top['views']}V)")
        else:
            print(f"{len(raw)} fetched, 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 2 complete. {len(all_results['accounts'])} accounts, {len(all_results['errors'])} errors.")
