from __future__ import annotations
import re
from typing import List, Optional

import dns.resolver
import dns.exception


def make_resolver(nameservers: Optional[List[str]], timeout: float) -> dns.resolver.Resolver:
    r = dns.resolver.Resolver(configure=True)
    if nameservers:
        r.nameservers = nameservers
    r.timeout = timeout
    r.lifetime = timeout
    return r


def query_txt(res: dns.resolver.Resolver, name: str) -> List[str]:
    try:
        ans = res.resolve(name, "TXT")
        records: List[str] = []
        for rr in ans:
            text = rr.to_text()
            parts = re.findall(r'"([^"]*)"', text)
            if parts:
                records.append("".join(parts))
            else:
                records.append(text.strip('"'))
        return records
    except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers, dns.exception.Timeout):
        return []
    except Exception:
        return []


def query_mx(res: dns.resolver.Resolver, name: str) -> List[str]:
    try:
        ans = res.resolve(name, "MX")
        ex = []
        for rr in ans:
            ex.append(str(rr.exchange).rstrip("."))
        return sorted(set(ex))
    except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers, dns.exception.Timeout):
        return []
    except Exception:
        return []
