# retoor <retoor@molodetz.nl>

from __future__ import annotations

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

CATEGORY = "security"

SECURITY_HEADERS = {
    "content-security-policy": ("Content-Security-Policy", LOW),
    "x-content-type-options": ("X-Content-Type-Options", LOW),
    "x-frame-options": ("X-Frame-Options", LOW),
    "referrer-policy": ("Referrer-Policy", LOW),
}


@page_check
def security_headers(page: PageContext, site: SiteContext) -> list:
    results = []
    for key, (label, severity) in SECURITY_HEADERS.items():
        present = bool(page.headers.get(key))
        results.append(
            ok_check(
                f"security.{key}",
                CATEGORY,
                label,
                present,
                severity=severity,
                value="present" if present else "missing",
                recommendation=f"Add the {label} response header.",
                warn=True,
                url=page.url,
            )
        )
    return results


@page_check
def tls_valid(page: PageContext, site: SiteContext) -> Check | None:
    if "tlsValid" not in page.metrics:
        return None
    valid = bool(page.metrics.get("tlsValid"))
    return ok_check(
        "security.tls",
        CATEGORY,
        "Valid TLS certificate",
        valid,
        severity=MEDIUM,
        value="valid" if valid else "invalid",
        recommendation="Serve a valid, unexpired TLS certificate.",
        url=page.url,
    )
