from __future__ import annotations
import re
from typing import Tuple

import tldextract
import idna


def normalize_domain(s: str) -> str:
    s = s.strip().lower()
    s = re.sub(r"^https?://", "", s)
    s = s.split("/")[0]
    s = s.split(":")[0]
    s = s.strip(".")
    return s


def extract_etld1_and_subdomain(domain_or_fqdn: str) -> Tuple[str, str, bool]:
    ext = tldextract.extract(domain_or_fqdn)
    if not ext.domain or not ext.suffix:
        return domain_or_fqdn, "", False
    registrable = f"{ext.domain}.{ext.suffix}"
    sub = ext.subdomain or ""
    fqdn_provided = (sub != "")
    return registrable, sub, fqdn_provided


def is_idn(domain: str) -> bool:
    return "xn--" in domain or any(ord(c) > 127 for c in domain)


def to_unicode(domain: str) -> str:
    labels = domain.split(".")
    out = []
    for lab in labels:
        if lab.startswith("xn--"):
            try:
                out.append(idna.decode(lab))
            except Exception:
                out.append(lab)
        else:
            out.append(lab)
    return ".".join(out)
