import logging
import os
import re
from typing import Optional
from urllib.parse import urlparse

import tldextract


log = logging.getLogger(__name__)


DOMAIN_PATTERN = (
    r"^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?"
    r"(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*"
    r"\.[a-zA-Z]{2,}$"
)


def extract_domain(url: Optional[str] = None) -> Optional[str]:
    if url:
        extracted = tldextract.extract(url)
        domain = f"{extracted.domain}.{extracted.suffix}"
        domain = domain.lower().strip()
        if is_valid_domain(domain):
            return domain
    return None


def is_valid_domain(domain: str) -> bool:
    if not domain:
        return False

    return bool(re.match(DOMAIN_PATTERN, domain))


def is_valid_url(url: str) -> bool:
    """validate url format"""
    try:
        result = urlparse(url)
        return all([result.scheme, result.netloc])
    except Exception as e:
        log.warning(f"invalid url format: {url}, error: {e}")
        return False


def get_filename_from_url(url: str) -> str:
    parsed = urlparse(url)
    return os.path.basename(parsed.path)
