"""Free public sources for the senses/ingestion layer."""
from __future__ import annotations

import gzip
import html
import inspect
import json
import os
import re
import time as _time
from urllib.parse import quote, urlencode

from . import ingestion


USER_AGENT = getattr(ingestion, "USER_AGENT", "Jarvis/1.0 (public research)")


def _get_json(url: str, headers: dict | None = None) -> dict | list:
    request_headers = {"User-Agent": USER_AGENT, "Accept": "application/json"}
    if headers:
        request_headers.update(headers)

    timeout = float(getattr(ingestion, "TIMEOUT", 20) or 20)
    timeout = max(10.0, min(timeout, 30.0))
    body = ingestion.http_get(url, headers=request_headers, timeout=timeout)

    if body[:2] == b"\x1f\x8b":
        body = gzip.decompress(body)

    text = body.decode("utf-8", errors="replace").lstrip()
    if text.startswith("<"):
        raise ValueError("source returned HTML instead of JSON: %s" % text[:120])
    try:
        data = json.loads(text)
    except ValueError:
        raise ValueError(
            "source returned non-JSON (%d bytes): %s" % (len(body), text[:160])
        )
    if not isinstance(data, (dict, list)):
        raise ValueError("source returned JSON with an unexpected shape")
    return data


def _plain(value) -> str:
    text = html.unescape(str(value or ""))
    text = re.sub(r"<[^>]+>", " ", text)
    return re.sub(r"\s+", " ", text).strip()


def _item(
    source: str,
    title: str,
    url: str | None,
    summary: str = "",
    published_at: str | None = None,
    author: str | None = None,
    score: int | None = None,
) -> dict:
    values = {
        "title": _plain(title),
        "url": url,
        "summary": _plain(summary),
        "published_at": published_at,
        "author": author,
        "score": score,
    }

    normalizer = ingestion.normalize_item
    parameters = inspect.signature(normalizer).parameters
    accepts_kwargs = any(
        parameter.kind == inspect.Parameter.VAR_KEYWORD
        for parameter in parameters.values()
    )
    if not accepts_kwargs:
        values = {key: value for key, value in values.items() if key in parameters}

    return normalizer(source, **values)


def fetch_bluesky(limit: int = 15) -> list[dict]:
    source = "bluesky"
    query = urlencode({"q": "small business OR contractor OR AI", "limit": max(1, min(limit, 100))})
    url = "https://public.api.bsky.app/xrpc/app.bsky.feed.searchPosts?" + query
    token = os.environ.get("JARVIS_BLUESKY_TOKEN", "").strip()
    headers = {"Authorization": "Bearer " + token} if token else None
    data = _get_json(url, headers)
    posts = data.get("posts", []) if isinstance(data, dict) else []

    items = []
    for post in posts:
        record = post.get("record") or {}
        author = post.get("author") or {}
        uri_parts = str(post.get("uri") or "").split("/")
        post_url = None
        if len(uri_parts) >= 4:
            post_url = "https://bsky.app/profile/%s/post/%s" % (
                quote(str(author.get("handle") or ""), safe=""),
                quote(uri_parts[-1], safe=""),
            )
        text = record.get("text") or ""
        items.append(
            _item(
                source,
                text[:180] or "Bluesky post",
                post_url,
                summary=text,
                published_at=record.get("createdAt") or post.get("indexedAt"),
                author=author.get("handle"),
                score=post.get("likeCount"),
            )
        )
    return items


def fetch_mastodon(limit: int = 15) -> list[dict]:
    source = "mastodon"
    tag = "smallbusiness"
    instances = ("mastodon.social", "fosstodon.org")
    last_error = None

    for instance in instances:
        url = "https://%s/api/v1/timelines/tag/%s?%s" % (
            instance,
            quote(tag, safe=""),
            urlencode({"limit": max(1, min(limit, 40))}),
        )
        try:
            data = _get_json(url, {"Accept": "application/json"})
        except Exception as exc:
            last_error = exc
            continue

        if not isinstance(data, list):
            raise ValueError("Mastodon returned an unexpected timeline shape")

        items = []
        for status in data:
            account = status.get("account") or {}
            items.append(
                _item(
                    source,
                    _plain(status.get("content"))[:180] or "Mastodon post",
                    status.get("url"),
                    summary=status.get("content") or status.get("spoiler_text") or "",
                    published_at=status.get("created_at"),
                    author=account.get("acct") or account.get("username"),
                    score=status.get("favourites_count"),
                )
            )
        return items

    raise RuntimeError("Mastodon instances failed: %s" % last_error)


def fetch_gdelt(limit: int = 15) -> list[dict]:
    source = "gdelt"
    params = {
        "query": '("small business" OR contractor OR automation)',
        "mode": "artlist",
        "format": "json",
        "maxrecords": max(1, min(limit, 75)),
        "sort": "HybridRel",
    }
    url = "https://api.gdeltproject.org/api/v2/doc/doc?" + urlencode(params)
    try:
        data = _get_json(url)
    except ValueError:
        _time.sleep(5.0)   # GDELT answers 200 with plain text while throttling
        data = _get_json(url)
    articles = data.get("articles", []) if isinstance(data, dict) else []

    return [
        _item(
            source,
            article.get("title") or "GDELT article",
            article.get("url"),
            summary=article.get("domain") or article.get("source") or "",
            published_at=article.get("seendate"),
            author=article.get("source"),
        )
        for article in articles
    ]


def fetch_github(limit: int = 15) -> list[dict]:
    source = "github"
    params = {
        "q": "AI automation",
        "sort": "updated",
        "order": "desc",
        "per_page": max(1, min(limit, 100)),
    }
    url = "https://api.github.com/search/repositories?" + urlencode(params)
    data = _get_json(url, {"Accept": "application/vnd.github+json"})
    repositories = data.get("items", []) if isinstance(data, dict) else []

    return [
        _item(
            source,
            repository.get("full_name") or repository.get("name") or "GitHub repository",
            repository.get("html_url"),
            summary=repository.get("description") or "",
            published_at=repository.get("updated_at"),
            author=(repository.get("owner") or {}).get("login"),
            score=repository.get("stargazers_count"),
        )
        for repository in repositories
    ]


def fetch_stackexchange(limit: int = 15) -> list[dict]:
    source = "stackexchange"
    params = {
        "order": "desc",
        "sort": "activity",
        "tagged": "python;machine-learning",
        "site": "stackoverflow",
        "pagesize": max(1, min(limit, 100)),
    }
    url = "https://api.stackexchange.com/2.3/questions?" + urlencode(params)
    data = _get_json(url)
    questions = data.get("items", []) if isinstance(data, dict) else []

    return [
        _item(
            source,
            question.get("title") or "Stack Exchange question",
            question.get("link"),
            summary="Score %s; answers %s" % (
                question.get("score", 0),
                question.get("answer_count", 0),
            ),
            published_at=question.get("last_activity_date"),
            author=(question.get("owner") or {}).get("display_name"),
            score=question.get("score"),
        )
        for question in questions
    ]


def fetch_youtube(channel_id: str, limit: int = 15) -> list[dict]:
    """Fetch a channel feed; channel IDs must be configured, never guessed."""
    source = "youtube/" + channel_id
    feed_url = "https://www.youtube.com/feeds/videos.xml?channel_id=" + quote(channel_id, safe="")
    return ingestion.fetch_rss(source, feed_url, limit)


def fetch_arxiv(limit: int = 15) -> list[dict]:
    """arXiv Atom feed — primary research, not commentary about it.

    Reuses ingestion.fetch_rss. The import is late on purpose: ingestion.py
    imports this module at module level, so a top-level import would be circular.
    """
    from .ingestion import fetch_rss

    query = urlencode(
        {
            "search_query": "cat:cs.AI OR cat:cs.LG OR cat:cs.CL",
            "sortBy": "submittedDate",
            "sortOrder": "descending",
            "max_results": max(1, min(limit, 50)),
        }
    )
    return fetch_rss("arxiv", "https://export.arxiv.org/api/query?" + query, limit)


def senses_sources() -> list[dict]:
    sources = [
        {
            "name": "bluesky",
            "kind": "json",
            "url": "https://public.api.bsky.app/xrpc/app.bsky.feed.searchPosts",
            "fetch": lambda limit: fetch_bluesky(limit),
        },
        {
            "name": "mastodon",
            "kind": "json",
            "url": "https://mastodon.social/api/v1/timelines/tag/smallbusiness",
            "fetch": lambda limit: fetch_mastodon(limit),
        },
        {
            "name": "gdelt",
            "kind": "json",
            "url": "https://api.gdeltproject.org/api/v2/doc/doc",
            "fetch": lambda limit: fetch_gdelt(limit),
        },
        {
            "name": "github",
            "kind": "json",
            "url": "https://api.github.com/search/repositories",
            "fetch": lambda limit: fetch_github(limit),
        },
        {
            "name": "stackexchange",
            "kind": "json",
            "url": "https://api.stackexchange.com/2.3/questions",
            "fetch": lambda limit: fetch_stackexchange(limit),
        },
        {
            "name": "arxiv",
            "kind": "atom",
            "url": "https://export.arxiv.org/api/query",
            "fetch": lambda limit: fetch_arxiv(limit),
        },
    ]

    channel_ids = [
        value.strip()
        for value in os.environ.get("JARVIS_YOUTUBE_CHANNELS", "").split(",")
        if value.strip()
    ]
    for channel_id in channel_ids:
        name = "youtube/" + channel_id
        feed_url = "https://www.youtube.com/feeds/videos.xml?channel_id=" + quote(channel_id, safe="")
        sources.append(
            {
                "name": name,
                "kind": "rss",
                "url": feed_url,
                "fetch": lambda limit, channel_id=channel_id: fetch_youtube(channel_id, limit),
            }
        )
    return sources


SENSES_SOURCES = senses_sources()


def fetch_reddit_fallback(subreddit: str, limit: int = 25) -> list[dict]:
    """Reddit's own JSON endpoint 403s from many networks. PullPush serves the same data."""
    source = "reddit/" + subreddit
    params = urlencode({
        "subreddit": subreddit,
        "size": max(1, min(int(limit), 100)),
        "sort": "desc",
    })
    url = "https://api.pullpush.io/reddit/search/submission/?" + params
    data = _get_json(url)
    rows = data.get("data", []) if isinstance(data, dict) else []
    items = []
    for row in rows:
        permalink = row.get("permalink") or ""
        items.append(
            _item(
                source,
                row.get("title") or "Reddit post",
                ("https://www.reddit.com" + permalink) if permalink else row.get("url"),
                summary=row.get("selftext") or "",
                published_at=row.get("created_utc"),
                author=row.get("author"),
                score=row.get("score"),
            )
        )
    return items


def fetch_reddit_rss(subreddit: str, limit: int = 25) -> list[dict]:
    """Reddit's .rss feed is a different endpoint from the JSON API and is often not blocked."""
    from .ingestion import fetch_rss
    url = "https://www.reddit.com/r/%s/.rss" % subreddit
    return fetch_rss("reddit/" + subreddit, url, limit)
