from __future__ import annotations
import re
from dataclasses import dataclass
import httpx


@dataclass
class HstsInfo:
    present: bool = False
    max_age: int = 0
    include_subdomains: bool = False
    preload: bool = False
    raw: str = ""
    error: str | None = None


async def fetch_hsts(host: str, port: int, timeout: float = 6.0) -> HstsInfo:
    url = f"https://{host}:{port}/" if port != 443 else f"https://{host}/"
    try:
        async with httpx.AsyncClient(
            timeout=timeout,
            follow_redirects=False,
            verify=False,
            headers={"User-Agent": "nercone-tls-test/1.0"},
        ) as client:
            resp = await client.get(url)
    except Exception as e:
        return HstsInfo(error=f"{e.__class__.__name__}: {e}")
    header = resp.headers.get("strict-transport-security", "")
    if not header:
        return HstsInfo(present=False, raw="")
    info = HstsInfo(present=True, raw=header)
    for token in header.split(";"):
        t = token.strip().lower()
        if t.startswith("max-age="):
            try:
                info.max_age = int(t.split("=", 1)[1])
            except ValueError:
                info.max_age = 0
        elif t == "includesubdomains":
            info.include_subdomains = True
        elif t == "preload":
            info.preload = True
    return info
