"""HTML to clean Markdown, with simple main-content detection.

Strategy:
1. Drop elements that are never content (script, style, nav, footer, forms, cookie banners...).
2. Prefer <main> or <article> if present; otherwise pick the block with the most paragraph text.
3. Convert the remaining tree to Markdown: headings, paragraphs, lists, links, emphasis,
   code, blockquotes, tables and images (alt text).
"""

from __future__ import annotations

import re
from dataclasses import dataclass, field
from html.parser import HTMLParser
from typing import Dict, List, Optional
from urllib.parse import urljoin

from .clean import clean_markdown, strip_tracking

VOID = {"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"}
DROP_TAGS = {"script", "style", "noscript", "template", "svg", "canvas", "iframe", "form", "button",
             "select", "textarea", "nav", "footer", "aside", "header", "dialog", "object", "head"}
NOISE_HINTS = re.compile(
    r"(^|[\s_-])(cookie|consent|banner|newsletter|subscribe|share|social|related|promo|advert|ads?|"
    r"sidebar|breadcrumb|comment|popup|modal|footer|nav|menu)([\s_-]|$)",
    re.IGNORECASE,
)
BLOCK = {"p", "div", "section", "article", "main", "ul", "ol", "li", "table", "tr", "blockquote", "pre",
         "h1", "h2", "h3", "h4", "h5", "h6", "figure", "figcaption", "dl", "dt", "dd", "hr", "br"}


@dataclass
class Node:
    tag: str
    attrs: Dict[str, str] = field(default_factory=dict)
    children: List["Node | str"] = field(default_factory=list)
    parent: Optional["Node"] = None


class _TreeBuilder(HTMLParser):
    """Tolerant tree builder: closes unclosed tags when a parent closes."""

    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.root = Node("root")
        self.cur = self.root
        self.title = ""
        self.meta: Dict[str, str] = {}
        self._in_title = False

    def handle_starttag(self, tag, attrs):
        a = {k: (v or "") for k, v in attrs}
        if tag == "title":
            self._in_title = True
        if tag == "meta":
            key = a.get("name") or a.get("property")
            if key and "content" in a:
                self.meta[key.lower()] = a["content"]
        if tag == "p" and self.cur.tag == "p":  # implicit </p>
            self.cur = self.cur.parent
        node = Node(tag, a, parent=self.cur)
        self.cur.children.append(node)
        if tag not in VOID:
            self.cur = node

    def handle_startendtag(self, tag, attrs):
        a = {k: (v or "") for k, v in attrs}
        self.cur.children.append(Node(tag, a, parent=self.cur))

    def handle_endtag(self, tag):
        if tag == "title":
            self._in_title = False
        n = self.cur
        while n is not self.root and n.tag != tag:
            n = n.parent
        if n is not self.root:
            self.cur = n.parent

    def handle_data(self, data):
        if self._in_title:
            self.title += data
        self.cur.children.append(data)


def _is_noise(n: Node) -> bool:
    if n.tag in DROP_TAGS:
        return True
    if "hidden" in n.attrs or n.attrs.get("aria-hidden") == "true":
        return True
    if "display:none" in n.attrs.get("style", "").replace(" ", "").lower():
        return True
    role = n.attrs.get("role", "")
    if role in {"navigation", "banner", "contentinfo", "complementary", "dialog", "alert"}:
        return True
    hint = f"{n.attrs.get('id', '')} {n.attrs.get('class', '')}"
    return bool(NOISE_HINTS.search(hint)) and n.tag not in {"main", "article", "body", "html"}


def _prune(n: Node) -> None:
    n.children = [c for c in n.children if isinstance(c, str) or not _is_noise(c)]
    for c in n.children:
        if isinstance(c, Node):
            _prune(c)


def _text_len(n: Node) -> int:
    total = 0
    for c in n.children:
        total += len(c.strip()) if isinstance(c, str) else _text_len(c)
    return total


def _para_score(n: Node) -> int:
    """Text inside <p>/<li>/<pre> descendants, minus link-heavy text."""
    score = 0
    for c in n.children:
        if isinstance(c, Node):
            if c.tag in {"p", "pre", "li", "blockquote", "td"}:
                score += _text_len(c) - _link_text(c) // 2
            else:
                score += _para_score(c)
    return score


def _link_text(n: Node) -> int:
    total = 0
    for c in n.children:
        if isinstance(c, Node):
            total += _text_len(c) if c.tag == "a" else _link_text(c)
    return total


def _find(n: Node, tag: str) -> List[Node]:
    out = []
    for c in n.children:
        if isinstance(c, Node):
            if c.tag == tag:
                out.append(c)
            out.extend(_find(c, tag))
    return out


def _best_block(root: Node) -> Node:
    for tag in ("main", "article"):
        found = _find(root, tag)
        if found:
            return max(found, key=_text_len)
    best, best_score = root, _para_score(root)
    # best_score stays the page total: candidates must hold at least 80% of it
    stack = [root]
    while stack:
        n = stack.pop()
        for c in n.children:
            if not isinstance(c, Node):
                continue
            if c.tag in {"div", "section", "td", "body"}:
                s = _para_score(c)
                # prefer the smallest container holding most of the paragraph text
                if s >= 0.8 * best_score and s > 0:
                    best = c
            stack.append(c)
    return best


class _MD:
    def __init__(self, base_url: str):
        self.base = base_url

    def inline(self, n: "Node | str") -> str:
        if isinstance(n, str):
            return re.sub(r"\s+", " ", n)
        t = n.tag
        inner = "".join(self.inline(c) for c in n.children)
        if t in {"strong", "b"}:
            s = inner.strip()
            return f"**{s}**" if s else ""
        if t in {"em", "i"}:
            s = inner.strip()
            return f"*{s}*" if s else ""
        if t == "code":
            return f"`{_text(n)}`"
        if t == "br":
            return "  \n"
        if t == "a":
            href = n.attrs.get("href", "").strip()
            s = inner.strip()
            if not s:
                return ""
            if not href or href.startswith(("javascript:", "#")):
                return s
            return f"[{s}]({strip_tracking(urljoin(self.base, href))})"
        if t == "img":
            alt = n.attrs.get("alt", "").strip()
            src = n.attrs.get("src", "")
            return f"![{alt}]({strip_tracking(urljoin(self.base, src))})" if alt and src else ""
        if t in BLOCK:
            return "\n\n" + self.block(n) + "\n\n"
        return inner

    def block(self, n: Node, depth: int = 0) -> str:
        t = n.tag
        if t in {"h1", "h2", "h3", "h4", "h5", "h6"}:
            text = " ".join("".join(self.inline(c) for c in n.children).split())
            return f"{'#' * int(t[1])} {text}" if text else ""
        if t == "p" or t == "figcaption":
            return "".join(self.inline(c) for c in n.children).strip()
        if t == "pre":
            code = _text(n, keep_ws=True).strip("\n")
            lang = ""
            for c in n.children:
                if isinstance(c, Node) and c.tag == "code":
                    m = re.search(r"language-([\w+-]+)", c.attrs.get("class", ""))
                    lang = m.group(1) if m else ""
            return f"```{lang}\n{code}\n```"
        if t in {"ul", "ol"}:
            lines = []
            i = 0
            for c in n.children:
                if isinstance(c, Node) and c.tag == "li":
                    i += 1
                    marker = f"{i}." if t == "ol" else "-"
                    body_parts, nested = [], []
                    for cc in c.children:
                        if isinstance(cc, Node) and cc.tag in {"ul", "ol"}:
                            nested.append(self.block(cc, depth + 1))
                        else:
                            body_parts.append(self.inline(cc))
                    body = " ".join("".join(body_parts).split())
                    lines.append("  " * depth + f"{marker} {body}")
                    lines.extend(x for x in nested if x)
            return "\n".join(lines)
        if t == "blockquote":
            inner = self.children_md(n)
            return "\n".join("> " + ln if ln else ">" for ln in inner.split("\n"))
        if t == "table":
            return self.table(n)
        if t == "hr":
            return "---"
        return self.children_md(n)

    def children_md(self, n: Node) -> str:
        parts, buf = [], ""
        for c in n.children:
            if isinstance(c, Node) and c.tag in BLOCK and c.tag != "br":
                if buf.strip():
                    parts.append(" ".join(buf.split()) if "  \n" not in buf else buf.strip())
                buf = ""
                b = self.block(c)
                if b.strip():
                    parts.append(b)
            else:
                buf += self.inline(c)
        if buf.strip():
            parts.append(" ".join(buf.split()))
        return "\n\n".join(parts)

    def table(self, n: Node) -> str:
        rows = []
        for tr in _find(n, "tr"):
            cells = [c for c in tr.children if isinstance(c, Node) and c.tag in {"td", "th"}]
            rows.append([" ".join("".join(self.inline(x) for x in c.children).split()).replace("|", "\\|")
                         for c in cells])
        rows = [r for r in rows if any(r)]
        if not rows:
            return ""
        width = max(len(r) for r in rows)
        rows = [r + [""] * (width - len(r)) for r in rows]
        out = ["| " + " | ".join(rows[0]) + " |", "|" + "---|" * width]
        out += ["| " + " | ".join(r) + " |" for r in rows[1:]]
        return "\n".join(out)


def _text(n: "Node | str", keep_ws: bool = False) -> str:
    if isinstance(n, str):
        return n if keep_ws else n
    return "".join(_text(c, keep_ws) for c in n.children)


@dataclass
class Document:
    url: str
    title: str
    markdown: str
    description: str = ""
    language: str = ""

    def with_front_matter(self) -> str:
        def q(s):
            return '"' + s.replace('\\', '\\\\').replace('"', '\\"') + '"'
        fm = ["---", f"url: {q(self.url)}", f"title: {q(self.title)}"]
        if self.description:
            fm.append(f"description: {q(self.description)}")
        if self.language:
            fm.append(f"language: {q(self.language)}")
        fm.append("---")
        return "\n".join(fm) + "\n\n" + self.markdown


def extract_main(html: str, url: str = "", main_only: bool = True) -> Document:
    tb = _TreeBuilder()
    tb.feed(html)
    tb.close()
    lang = ""
    for c in tb.root.children:
        if isinstance(c, Node) and c.tag == "html":
            lang = c.attrs.get("lang", "")
    _prune(tb.root)
    node = _best_block(tb.root) if main_only else tb.root
    md = _MD(url).block(node)
    md = clean_markdown(md)
    title = " ".join(tb.title.split()) or tb.meta.get("og:title", "")
    desc = tb.meta.get("description") or tb.meta.get("og:description", "")
    return Document(url, title, md, desc, lang)


def html_to_markdown(html: str, url: str = "", main_only: bool = True) -> str:
    return extract_main(html, url, main_only).markdown
