#!/usr/bin/env python3
"""X Account Monitor — Scan Chunk 2 (remaining ~22 accounts)
Incremental save to scan_results_2026-06-16_CHUNK2.json
Resume-safe: checks done_handles before re-fetching."""

import urllib.request
import json
import time
import os
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-16_CHUNK2.json"
DATE_STR = "2026-06-16"

# Remaining accounts: auto-discovered + newly added
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",
]

CUTOFF = datetime(2026, 6, 13, 0, 0, 0, tzinfo=timezone.utc)


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 Exception:
        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")
    except Exception as e:
        return {"error": str(e)}
    try:
        data = json.loads(body, strict=False)
    except json.JSONDecodeError as e:
        return {"error": f"JSON decode: {e}", "raw": body[:200]}
    if isinstance(data, dict) and "tweets" in data:
        return data["tweets"]
    elif isinstance(data, list):
        return data
    elif isinstance(data, dict) and "errors" in data:
        return {"error": str(data["errors"])}
    elif isinstance(data, dict) and "error" in data:
        return {"error": data["error"]}
    else:
        return []


def process_tweets(handle, raw_tweets):
    if isinstance(raw_tweets, dict) and "error" in raw_tweets:
        return {
            "handle": handle,
            "tweets": [],
            "recent_count": 0,
            "qualifying_count": 0,
            "error": raw_tweets["error"],
        }
    if not isinstance(raw_tweets, list):
        raw_tweets = []
    processed = []
    for t in raw_tweets:
        if not isinstance(t, dict):
            continue
        created_at = t.get("createdAt", "")
        dt = parse_date(created_at)
        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
        tweet_text = t.get("text", "")
        tweet_id = t.get("id", "")
        score = likes + (retweets * 2) + replies + (views / 100)
        author = t.get("author", {})
        author_name = author.get("userName", handle)
        followers = author.get("followers", 0)
        processed.append({
            "id": tweet_id,
            "text": tweet_text,
            "date": dt.strftime("%Y-%m-%d") if dt else "",
            "createdAt": created_at,
            "likes": int(likes),
            "retweets": int(retweets),
            "replies": int(replies),
            "views": int(views),
            "bookmarks": int(bookmarks),
            "score": round(score, 1),
            "author_name": author_name,
            "followers": int(followers) if followers else 0,
        })
    recent = [t for t in processed if t["date"]]
    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)
    return {
        "handle": handle,
        "tweets": qualifying,
        "recent_count": len(recent),
        "qualifying_count": len(qualifying),
        "total_fetched": len(processed),
    }


def main():
    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
            for acc in all_results.get("accounts", []):
                done_handles.add(acc["handle"])
            print(f"Resuming from {len(done_handles)} already-scanned accounts")
        except Exception:
            pass
    for i, handle in enumerate(HANDLES):
        if handle in done_handles:
            print(f"  [{i+1}/{len(HANDLES)}] @{handle} — SKIP (already scanned)")
            continue
        print(f"  [{i+1}/{len(HANDLES)}] @{handle}...", end=" ", flush=True)
        raw = fetch_tweets(handle)
        if isinstance(raw, dict) and "error" in raw:
            print(f"ERROR: {raw['error'][:80]}")
            all_results["errors"].append({"handle": handle, "error": raw["error"]})
        else:
            account_data = process_tweets(handle, raw)
            all_results["accounts"].append(account_data)
            print(f"{account_data['recent_count']} recent, {account_data['qualifying_count']} qualifying")
        tmp_path = f"{RESULTS_FILE}.tmp"
        with open(tmp_path, "w") as f:
            json.dump(all_results, f, indent=2)
        time.sleep(1)
    final_tmp = f"{RESULTS_FILE}.tmp"
    if os.path.exists(final_tmp):
        os.rename(final_tmp, RESULTS_FILE)
    print(f"\nDone. Saved to {RESULTS_FILE}")
    print(f"  Accounts: {len(all_results['accounts'])}, Errors: {len(all_results['errors'])}")


if __name__ == "__main__":
    main()
