"""StackOverflow site preset."""
import re
from urllib.parse import urlparse


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

    def extract(self, url):
        try:
            m = re.search(r'/questions/(\d+)', urlparse(url).path)
            if m:
                qid = m.group(1)
                resp = self.client.fetch(f"https://api.stackexchange.com/2.3/questions/{qid}?site=stackoverflow", timeout=10)
            else:
                resp = self.client.fetch("https://api.stackexchange.com/2.3/questions?order=desc&sort=hot&site=stackoverflow&pagesize=10", timeout=10)
            if resp.status_code == 200:
                d = resp.json()
                items = d.get("items", [])
                if items:
                    q = items[0]
                    return {"success": True, "data": {
                        "title": q.get("title"),
                        "score": q.get("score"),
                        "answer_count": q.get("answer_count"),
                        "is_answered": q.get("is_answered"),
                        "tags": q.get("tags"),
                        "link": q.get("link"),
                    }, "source": "stackexchange-api", "error": None}
            return {"success": False, "data": {}, "source": "stackexchange-api", "error": "Not found"}
        except Exception as e:
            return {"success": False, "data": {}, "source": "stackexchange-api", "error": str(e)}
