"""Extract subdomain from URL or domain."""

from typing import Dict, Any
from urllib.parse import urlparse

# Optional dependency
try:
    import tldextract

    HAS_TLDEXTRACT = True
except ImportError:
    HAS_TLDEXTRACT = False


def extract_subdomain(value: str) -> Dict[str, Any]:
    """
    Extract subdomain from a URL or domain.

    Examples:
        "app.hubspot.com" -> "app"
        "eu-west-1.aws.amazon.com" -> "eu-west-1"
        "www.example.com" -> "www"
        "example.com" -> ""
    """
    s = (value or "").strip().lower()
    if not s:
        return {"value": ""}

    # Add protocol if missing for urlparse
    if "://" not in s:
        s = f"https://{s}"

    if HAS_TLDEXTRACT:
        try:
            # Use tldextract for better subdomain extraction
            extracted = tldextract.extract(s)
            subdomain = extracted.subdomain

            # Return subdomain, or empty string if none
            return {
                "value": subdomain or "",
                "full_domain": f"{extracted.domain}.{extracted.suffix}"
                if extracted.domain
                else "",
                "suffix": extracted.suffix,
                "method": "tldextract",
            }
        except Exception:
            pass  # Fall through to basic parsing

    # Fallback to simple parsing
    try:
        parsed = urlparse(s)
        hostname = parsed.hostname or parsed.path.split("/")[0]
        parts = hostname.split(".")

        # Simple heuristic: if more than 2 parts, first parts are subdomain
        if len(parts) > 2:
            # Check if last part is a common TLD
            common_tlds = {
                "com",
                "org",
                "net",
                "io",
                "co",
                "uk",
                "de",
                "fr",
                "jp",
                "cn",
                "app",
            }
            if parts[-1] in common_tlds:
                # If 2nd to last is also a TLD component (like co.uk), adjust
                if parts[-2] in {"co", "ac", "gov", "edu", "net", "org"}:
                    subdomain = ".".join(parts[:-3]) if len(parts) > 3 else ""
                else:
                    subdomain = ".".join(parts[:-2])
            else:
                subdomain = ".".join(parts[:-2])
            return {"value": subdomain, "method": "basic"}

        return {"value": "", "method": "basic"}
    except Exception:
        return {"value": "", "method": "basic"}
