from __future__ import annotations
import asyncio
from dataclasses import dataclass, field


@dataclass
class CaaResult:
    host: str
    records: list[str] = field(default_factory=list)
    effective_host: str = ""
    error: str | None = None


async def lookup_caa(host: str, timeout: float = 5.0) -> CaaResult:
    try:
        import dns.asyncresolver
    except Exception as e:
        return CaaResult(host=host, error=f"dnspython missing: {e}")

    resolver = dns.asyncresolver.Resolver()
    resolver.lifetime = timeout
    labels = host.strip(".").split(".")
    for i in range(len(labels)):
        name = ".".join(labels[i:])
        if not name or "." not in name and i > 0:
            continue
        try:
            ans = await resolver.resolve(name, "CAA")
        except Exception:
            continue
        records: list[str] = []
        for r in ans:
            try:
                records.append(r.to_text())
            except Exception:
                continue
        if records:
            return CaaResult(host=host, records=records, effective_host=name)
    return CaaResult(host=host, records=[], effective_host="", error="no CAA records found up to TLD")
