"""Sample anonymized original tweets from an X (Twitter) archive into Markdown.

Place this script in the root folder of your unzipped X archive (next to the
`data/` folder containing `tweets.js`, `note-tweet.js`, and `account.js`), then
update `EXCLUDED_KEYWORDS_RE` with your own identifying names/handles and run:

    python sample_tweets.py -n 3000 -o tweets_sample.md
"""

import argparse
import html
import json
import random
import re
from datetime import datetime, timedelta
from pathlib import Path

ROOT = Path(__file__).resolve().parent
TCO_RE = re.compile(r"https?://t\.co/\S+")

# Replace with your own name, surname, or nicknames to keep the sample blind
# (set to None if you do not want keyword-based filtering).
EXCLUDED_KEYWORDS_RE = re.compile(r"your_name|your_surname|your_handle", re.IGNORECASE)


def load_ytd_js(path: Path):
    text = path.read_text(encoding="utf-8")
    return json.loads(text[text.index("[") :])


def norm_prefix(s: str) -> str:
    s = html.unescape(s)
    s = TCO_RE.sub("", s)
    s = re.sub(r"^(@\w+\s+)+", "", s)
    s = re.sub(r"\s+", " ", s).strip()
    return s[:40]


def load_original_posts(root: Path):
    account = load_ytd_js(root / "data" / "account.js")[0]["account"]
    username = account.get("username", "")
    display_name = account.get("accountDisplayName", "")

    raw_tweets = [x["tweet"] for x in load_ytd_js(root / "data" / "tweets.js")]
    note_path = root / "data" / "note-tweet.js"
    raw_notes = [x["noteTweet"] for x in load_ytd_js(note_path)] if note_path.exists() else []

    note_by_sec = {}
    for n in raw_notes:
        dt = datetime.strptime(n["createdAt"][:19], "%Y-%m-%dT%H:%M:%S")
        note_by_sec.setdefault(dt, []).append(n)

    def match_note_tweet(tweet, dt):
        t_pref = norm_prefix(tweet["full_text"])
        if not t_pref:
            return None
        for delta in (0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5):
            for n in note_by_sec.get(dt + timedelta(seconds=delta), []):
                n_text = n.get("core", {}).get("text", "")
                n_pref = norm_prefix(n_text)
                if not n_pref:
                    continue
                cmp_len = min(20, len(t_pref), len(n_pref))
                if cmp_len >= 8 and t_pref[:cmp_len] == n_pref[:cmp_len]:
                    return n
        return None

    def expand_text(tweet, note):
        if note is not None:
            text = html.unescape(note["core"]["text"])
            for u in note.get("core", {}).get("urls", []):
                short = u.get("shortUrl")
                expanded = u.get("expandedUrl")
                if short and expanded:
                    text = text.replace(short, expanded)
        else:
            text = html.unescape(tweet["full_text"])
            for u in tweet.get("entities", {}).get("urls", []):
                short = u.get("url")
                expanded = u.get("expanded_url")
                if short and expanded:
                    text = text.replace(short, expanded)

        media_items = (
            tweet.get("extended_entities", {}).get("media")
            or tweet.get("entities", {}).get("media")
            or []
        )
        media_urls = []
        seen_short = set()
        seen_exp = set()
        for m in media_items:
            short = m.get("url")
            if short and short not in seen_short:
                seen_short.add(short)
                text = text.replace(short, "").rstrip()
            exp = m.get("expanded_url") or m.get("media_url_https")
            if exp and exp not in seen_exp:
                seen_exp.add(exp)
                media_urls.append((m.get("type", "media"), exp))

        return text.strip(), media_urls

    posts = []
    for t in raw_tweets:
        ft = t.get("full_text", "")
        if ft.startswith("RT @"):
            continue
        is_reply = bool(t.get("in_reply_to_status_id_str") or t.get("in_reply_to_user_id_str"))
        dt = datetime.strptime(t["created_at"], "%a %b %d %H:%M:%S +0000 %Y")
        note = match_note_tweet(t, dt)
        text, media_urls = expand_text(t, note)
        is_long = (note is not None) or (len(text) > 280)
        has_media = bool(media_urls)
        if is_reply:
            if len(text) <= 400:
                continue
        elif has_media and not is_long:
            continue
        if not text:
            continue
        if EXCLUDED_KEYWORDS_RE is not None and EXCLUDED_KEYWORDS_RE.search(text):
            continue
        posts.append(
            {
                "id": t["id_str"],
                "dt": dt,
                "text": text,
                "is_long": is_long,
                "is_reply": is_reply,
            }
        )

    return username, display_name, posts


def sample_posts(posts, count: int, min_long: int, min_replies: int, seed=None):
    rng = random.Random(seed)
    total = min(count, len(posts))
    long_posts = [p for p in posts if p["is_long"]]
    reply_posts = [p for p in posts if p["is_reply"]]

    required_replies = min(min_replies, len(reply_posts), total)
    required_long = min(min_long, len(long_posts), total)

    # Start with a uniform random sample of all posts
    picked = rng.sample(posts, total)

    # Guarantee at least `required_replies` long replies
    picked_replies = [p for p in picked if p["is_reply"]]
    if len(picked_replies) < required_replies:
        deficit = required_replies - len(picked_replies)
        picked_ids = {p["id"] for p in picked}
        remaining_replies = [p for p in reply_posts if p["id"] not in picked_ids]
        removable_short = [p for p in picked if not p["is_reply"] and not p["is_long"]]
        removable_other = [p for p in picked if not p["is_reply"] and p["is_long"]]
        to_remove = rng.sample(removable_short, min(deficit, len(removable_short)))
        if len(to_remove) < deficit:
            to_remove += rng.sample(removable_other, deficit - len(to_remove))
        to_remove_ids = {p["id"] for p in to_remove}
        to_add = rng.sample(remaining_replies, deficit)
        picked = [p for p in picked if p["id"] not in to_remove_ids] + to_add

    # Guarantee at least `required_long` long-form posts (eligible replies are >400 chars, so is_long=True)
    picked_long = [p for p in picked if p["is_long"]]
    if len(picked_long) < required_long:
        deficit = required_long - len(picked_long)
        picked_ids = {p["id"] for p in picked}
        remaining_long = [p for p in long_posts if p["id"] not in picked_ids]
        picked_short = [p for p in picked if not p["is_long"]]

        to_add = rng.sample(remaining_long, deficit)
        to_remove_ids = {p["id"] for p in rng.sample(picked_short, deficit)}
        picked = [p for p in picked if p["id"] not in to_remove_ids] + to_add

    picked.sort(key=lambda p: (p["dt"], int(p["id"])), reverse=True)
    return picked


def write_markdown(out_path: Path, sampled):
    long_count = sum(1 for p in sampled if p["is_long"])
    reply_count = sum(1 for p in sampled if p["is_reply"])
    content = "\n\n---\n\n".join(p["text"] for p in sampled) + "\n"
    out_path.write_text(content, encoding="utf-8")
    return len(content), long_count, reply_count


def main():
    parser = argparse.ArgumentParser(description="Sample original tweets from an X/Twitter archive to Markdown.")
    parser.add_argument("-n", "--count", type=int, default=3000, help="Number of tweets to sample (default: 3000)")
    parser.add_argument("--min-long", type=int, default=100, help="Minimum number of long-form posts (default: 100)")
    parser.add_argument("--min-replies", type=int, default=50, help="Minimum number of >400-char replies (default: 50)")
    parser.add_argument("-o", "--output", type=str, default="tweets_sample.md", help="Output markdown filename")
    parser.add_argument("--seed", type=int, default=None, help="Optional random seed for reproducibility")
    args = parser.parse_args()

    _, _, posts = load_original_posts(ROOT)
    sampled = sample_posts(
        posts,
        count=args.count,
        min_long=args.min_long,
        min_replies=args.min_replies,
        seed=args.seed,
    )

    out_path = Path(args.output)
    if not out_path.is_absolute():
        out_path = ROOT / out_path

    char_count, long_count, reply_count = write_markdown(out_path, sampled)
    print(
        f"Saved {len(sampled)} sampled tweets ({long_count} long-form, {reply_count} replies >400 chars) "
        f"from {len(posts):,} eligible posts to:"
    )
    print(f"  {out_path}")
    print(f"Size: {char_count:,} characters")


if __name__ == "__main__":
    main()
