# retoor <retoor@molodetz.nl>

from __future__ import annotations

from urllib.parse import urlparse

from .base import (
    MEDIUM,
    LOW,
    INFO,
    Check,
    PageContext,
    SiteContext,
    ok_check,
    page_check,
)

CATEGORY = "links"

GENERIC_ANCHORS = {
    "click here",
    "here",
    "read more",
    "more",
    "link",
    "this",
    "this page",
}


@page_check
def link_counts(page: PageContext, site: SiteContext) -> Check:
    links = page.dom.get("links", []) or []
    host = site.base_host
    internal = 0
    external = 0
    for link in links:
        href = link.get("href", "")
        netloc = urlparse(href).netloc
        if not netloc or netloc == host:
            internal += 1
        else:
            external += 1
    return Check(
        "links.counts",
        CATEGORY,
        "Link profile",
        INFO,
        INFO,
        value=f"{internal} internal, {external} external",
        details={"internal": internal, "external": external},
        url=page.url,
    )


@page_check
def internal_links_present(page: PageContext, site: SiteContext) -> Check:
    links = page.dom.get("links", []) or []
    host = site.base_host
    internal = [
        link
        for link in links
        if not urlparse(link.get("href", "")).netloc
        or urlparse(link.get("href", "")).netloc == host
    ]
    return ok_check(
        "links.internal_present",
        CATEGORY,
        "Internal links",
        len(internal) >= 1,
        severity=LOW,
        value=f"{len(internal)} internal link(s)",
        recommendation="Add internal links so crawlers can discover related pages.",
        warn=True,
        url=page.url,
    )


@page_check
def generic_anchors(page: PageContext, site: SiteContext) -> Check:
    links = page.dom.get("links", []) or []
    generic = [
        link
        for link in links
        if (link.get("text", "") or "").strip().lower() in GENERIC_ANCHORS
    ]
    passed = not generic
    return ok_check(
        "links.anchor_text",
        CATEGORY,
        "Descriptive anchor text",
        passed,
        severity=LOW,
        value="descriptive" if passed else f"{len(generic)} generic anchor(s)",
        recommendation="Replace generic anchors like 'click here' with descriptive text.",
        warn=True,
        details={"samples": [link.get("href", "") for link in generic[:10]]},
        url=page.url,
    )
