"""
Reddit Client — Public JSON Endpoints (No Auth Required)
==========================================================
Uses reddit.com's public .json endpoints. No API key, no PRAW, no approval.
Rate limit: ~10 requests/min. Plenty for our use case.
"""

import requests
import time
import random
from datetime import datetime, timezone

USER_AGENTS = [
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.2 Safari/605.1.15",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:134.0) Gecko/20100101 Firefox/134.0",
]

_last_request_time = 0
MIN_REQUEST_INTERVAL = 6.5  # ~10 req/min, stay safe


def _get_headers():
    return {
        "User-Agent": random.choice(USER_AGENTS),
        "Accept": "application/json",
    }


def _rate_limit():
    global _last_request_time
    elapsed = time.time() - _last_request_time
    if elapsed < MIN_REQUEST_INTERVAL:
        wait = MIN_REQUEST_INTERVAL - elapsed + random.uniform(0.5, 1.5)
        time.sleep(wait)
    _last_request_time = time.time()


def _fetch_json(url, params=None):
    _rate_limit()
    try:
        resp = requests.get(url, headers=_get_headers(), params=params, timeout=15)
        if resp.status_code == 429:
            print("  ⚠️  Rate limited. Waiting 30s...")
            time.sleep(30)
            resp = requests.get(url, headers=_get_headers(), params=params, timeout=15)
        if resp.status_code == 403:
            print(f"  ⚠️  403 Forbidden: {url}")
            return None
        resp.raise_for_status()
        return resp.json()
    except requests.exceptions.RequestException as e:
        print(f"  ❌ Request failed: {e}")
        return None


def _parse_post(post_data):
    d = post_data.get("data", {})
    now_utc = datetime.now(timezone.utc).timestamp()
    created = d.get("created_utc", now_utc)
    age_hours = (now_utc - created) / 3600

    return {
        "post_id": d.get("id", ""),
        "subreddit": d.get("subreddit", ""),
        "title": d.get("title", ""),
        "selftext": (d.get("selftext", "") or "")[:2000],
        "author": d.get("author", "[deleted]"),
        "score": d.get("score", 0),
        "upvote_ratio": d.get("upvote_ratio", 0),
        "num_comments": d.get("num_comments", 0),
        "url": f"https://reddit.com{d.get('permalink', '')}",
        "permalink": d.get("permalink", ""),
        "created_utc": created,
        "age_hours": round(age_hours, 1),
        "is_self": d.get("is_self", True),
        "link_flair_text": d.get("link_flair_text", ""),
    }


def _parse_comment(comment_data):
    d = comment_data.get("data", {})
    if d.get("body") is None:
        return None
    return {
        "id": d.get("id", ""),
        "author": d.get("author", "[deleted]"),
        "body": d.get("body", ""),
        "score": d.get("score", 0),
        "is_op": d.get("is_submitter", False),
        "created_utc": d.get("created_utc", 0),
    }


def get_new_posts(subreddit_name, limit=25):
    url = f"https://www.reddit.com/r/{subreddit_name}/new.json"
    data = _fetch_json(url, params={"limit": limit, "raw_json": 1})
    if not data:
        return []
    posts = []
    for child in data.get("data", {}).get("children", []):
        if child.get("kind") == "t3":
            posts.append(_parse_post(child))
    return posts


def get_rising_posts(subreddit_name, limit=25):
    url = f"https://www.reddit.com/r/{subreddit_name}/rising.json"
    data = _fetch_json(url, params={"limit": limit, "raw_json": 1})
    if not data:
        return []
    posts = []
    for child in data.get("data", {}).get("children", []):
        if child.get("kind") == "t3":
            posts.append(_parse_post(child))
    return posts


def get_hot_posts(subreddit_name, limit=10):
    url = f"https://www.reddit.com/r/{subreddit_name}/hot.json"
    data = _fetch_json(url, params={"limit": limit, "raw_json": 1})
    if not data:
        return []
    posts = []
    for child in data.get("data", {}).get("children", []):
        if child.get("kind") == "t3":
            posts.append(_parse_post(child))
    return posts


def search_subreddit(subreddit_name, query, limit=15, sort="new"):
    url = f"https://www.reddit.com/r/{subreddit_name}/search.json"
    params = {
        "q": query,
        "restrict_sr": "on",
        "sort": sort,
        "t": "week",
        "limit": limit,
        "raw_json": 1,
    }
    data = _fetch_json(url, params=params)
    if not data:
        return []
    posts = []
    for child in data.get("data", {}).get("children", []):
        if child.get("kind") == "t3":
            posts.append(_parse_post(child))
    return posts


def get_post_with_comments(post_id, comment_limit=30):
    url = f"https://www.reddit.com/comments/{post_id}.json"
    data = _fetch_json(url, params={"limit": comment_limit, "sort": "best", "raw_json": 1})
    if not data or not isinstance(data, list) or len(data) < 2:
        return None

    post_children = data[0].get("data", {}).get("children", [])
    if not post_children:
        return None
    post = _parse_post(post_children[0])

    comments = []
    comment_children = data[1].get("data", {}).get("children", [])
    for child in comment_children[:comment_limit]:
        if child.get("kind") == "t1":
            c = _parse_comment(child)
            if c:
                comments.append(c)

    post["comments"] = comments
    return post


def get_user_about(username):
    url = f"https://www.reddit.com/user/{username}/about.json"
    data = _fetch_json(url)
    if not data:
        return {"error": "Could not fetch user info", "total_karma": 0, "comment_karma": 0, "link_karma": 0, "account_age_days": 0}

    d = data.get("data", {})
    created = d.get("created_utc", 0)
    now = datetime.now(timezone.utc).timestamp()
    age_days = int((now - created) / 86400) if created else 0

    return {
        "username": d.get("name", username),
        "comment_karma": d.get("comment_karma", 0),
        "link_karma": d.get("link_karma", 0),
        "total_karma": d.get("total_karma", d.get("comment_karma", 0) + d.get("link_karma", 0)),
        "account_age_days": age_days,
        "created_utc": created,
    }


def get_user_comments(username, limit=25):
    url = f"https://www.reddit.com/user/{username}/comments.json"
    data = _fetch_json(url, params={"limit": limit, "sort": "new", "raw_json": 1})
    if not data:
        return []

    comments = []
    for child in data.get("data", {}).get("children", []):
        if child.get("kind") == "t1":
            d = child.get("data", {})
            comments.append({
                "id": d.get("id", ""),
                "subreddit": d.get("subreddit", ""),
                "body": d.get("body", ""),
                "score": d.get("score", 0),
                "post_title": d.get("link_title", ""),
                "created_utc": d.get("created_utc", 0),
                "permalink": f"https://reddit.com{d.get('permalink', '')}",
            })
    return comments
