"""Small breadth-first, same-site crawler that yields LLM-ready documents."""

from __future__ import annotations

import re
from collections import deque
from typing import Callable, Iterator, Optional, Set
from urllib.parse import urljoin, urlsplit, urlunsplit

from .clean import strip_tracking
from .extract import Document, extract_main
from .fetch import PoliteFetcher

SKIP_EXT = re.compile(r"\.(png|jpe?g|gif|webp|svg|ico|pdf|zip|gz|tar|mp[34]|mov|avi|css|js|woff2?|ttf|xml|json)$",
                      re.IGNORECASE)
_HREF = re.compile(r"""<a\s[^>]*?href\s*=\s*["']([^"'#]+)""", re.IGNORECASE)


def normalize_url(url: str) -> str:
    """Lowercase scheme and host, drop fragments and tracking params, remove default ports
    and trailing slash differences (except for the root path)."""
    url = strip_tracking(url)
    p = urlsplit(url)
    host = (p.hostname or "").lower()
    port = p.port
    netloc = host if port in (None, 80, 443) else f"{host}:{port}"
    path = p.path or "/"
    if len(path) > 1 and path.endswith("/"):
        path = path[:-1]
    return urlunsplit((p.scheme.lower(), netloc, path, p.query, ""))


def crawl(start_url: str, fetcher: Optional[PoliteFetcher] = None, max_pages: int = 50, max_depth: int = 2,
          same_host: bool = True, include: Optional[Callable[[str], bool]] = None) -> Iterator[Document]:
    fetcher = fetcher or PoliteFetcher()
    start = normalize_url(start_url)
    host = urlsplit(start).netloc
    seen: Set[str] = {start}
    queue = deque([(start, 0)])
    yielded = 0
    while queue and yielded < max_pages:
        url, depth = queue.popleft()
        res = fetcher.get(url)
        if not res.ok or "html" not in res.content_type:
            continue
        doc = extract_main(res.text, res.url)
        if doc.markdown.strip():
            yielded += 1
            yield doc
        if depth >= max_depth:
            continue
        for href in _HREF.findall(res.text):
            nxt = normalize_url(urljoin(res.url, href.strip()))
            p = urlsplit(nxt)
            if p.scheme not in ("http", "https") or SKIP_EXT.search(p.path):
                continue
            if same_host and p.netloc != host:
                continue
            if include and not include(nxt):
                continue
            if nxt not in seen:
                seen.add(nxt)
                queue.append((nxt, depth + 1))
