"""HTML source parser — extracts headings, IDs, script/link refs."""

from __future__ import annotations

import re
from html.parser import HTMLParser

from codectx.parser.types import DependencyRecord, EntityRecord, ParseResult

_HEADING_TAGS = {"h1", "h2", "h3", "h4", "h5", "h6"}


class _HtmlStructureParser(HTMLParser):
    def __init__(self) -> None:
        super().__init__()
        self._current_line = 1
        self.entities: list[EntityRecord] = []
        self.deps: list[DependencyRecord] = []
        self._in_heading: str | None = None
        self._heading_text: list[str] = []
        self._heading_line = 1
        self._raw_lines: list[str] = []

    def feed_lines(self, content: str) -> None:
        self._raw_lines = content.splitlines()
        self.feed(content)

    def _getpos_line(self) -> int:
        line, _ = self.getpos()
        return line

    def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
        attr_dict = dict(attrs)
        ln = self._getpos_line()

        if tag in _HEADING_TAGS:
            self._in_heading = tag
            self._heading_line = ln
            self._heading_text = []

        if tag == "script":
            src = attr_dict.get("src")
            if src:
                self.deps.append(DependencyRecord(path=src, type="script", line_number=ln))

        if tag == "link":
            href = attr_dict.get("href")
            rel = attr_dict.get("rel", "")
            if href:
                self.deps.append(DependencyRecord(path=href, type=rel or "link", line_number=ln))

        if tag == "a":
            href = attr_dict.get("href")
            if href and not href.startswith("#"):
                self.deps.append(DependencyRecord(path=href, type="href", line_number=ln))

        elem_id = attr_dict.get("id")
        if elem_id and tag not in _HEADING_TAGS:
            self.entities.append(EntityRecord(
                name=elem_id, qualified_name=f"#{elem_id}", type="element",
                start_line=ln, end_line=ln, language="html",
            ))

    def handle_endtag(self, tag: str) -> None:
        if tag == self._in_heading and self._heading_text:
            text = " ".join(self._heading_text).strip()
            if text:
                self.entities.append(EntityRecord(
                    name=text, qualified_name=text, type="heading",
                    kind=self._in_heading,
                    start_line=self._heading_line, end_line=self._heading_line,
                    language="html",
                ))
            self._in_heading = None
            self._heading_text = []

    def handle_data(self, data: str) -> None:
        if self._in_heading:
            text = data.strip()
            if text:
                self._heading_text.append(text)


def parse_html(file_path: str, content: str) -> ParseResult:
    result = ParseResult(file_path=file_path, language="html")
    parser = _HtmlStructureParser()
    try:
        parser.feed_lines(content)
        result.entities.extend(parser.entities)
        result.dependencies.extend(parser.deps)
    except Exception:
        pass
    return result
