"""Hacker News site preset."""
import re
from urllib.parse import urlparse, parse_qs


class HackerNews:
    def __init__(self, client):
        self.client = client

    def extract(self, url):
        try:
            parsed = urlparse(url)
            qs = parse_qs(parsed.query)
            item_id = qs.get("id", [None])[0]
            if not item_id:
                m = re.search(r'/item/(\d+)', parsed.path)
                if m:
                    item_id = m.group(1)
            if item_id:
                resp = self.client.fetch(f"https://hacker-news.firebaseio.com/v0/item/{item_id}.json", timeout=10)
                if resp.status_code == 200:
                    d = resp.json()
                    return {"success": True, "data": {
                        "title": d.get("title"),
                        "score": d.get("score"),
                        "author": d.get("by"),
                        "url": d.get("url"),
                        "descendants": d.get("descendants"),
                    }, "source": "hn-api", "error": None}
            else:
                resp = self.client.fetch("https://hacker-news.firebaseio.com/v0/topstories.json", timeout=10)
                if resp.status_code == 200:
                    ids = resp.json()[:10]
                    return {"success": True, "data": {"top_story_ids": ids}, "source": "hn-api", "error": None}
            return {"success": False, "data": {}, "source": "hn-api", "error": "Failed to fetch"}
        except Exception as e:
            return {"success": False, "data": {}, "source": "hn-api", "error": str(e)}
