# -*- coding: utf-8 -*-

from typing import Any
from urllib.parse import parse_qs, urlencode, urljoin, urlparse
from ddans.common.type import UrlData
from ddans.native.hook import NHook


class NUrl:

    @staticmethod
    def join_urls(base_url, *args):
        # 移除每个部分开头和结尾的斜杠，并过滤掉空字符串
        parts = [part.strip('/') for part in args if part]
        # 确保 base_url 以单个斜杠结尾
        base_url = base_url.rstrip('/') + '/'
        full_url = base_url
        for part in parts:
            full_url = urljoin(full_url, part + '/')
        return full_url.rstrip('/')

    @staticmethod
    def url_parse(url: str):
        if not NHook.isvalid_str(url):
            return None
        return NHook.safe_func(urlparse, url, allow_fragments=False)

    @staticmethod
    def url_query(params: Any | None = None, prefix: str = ''):
        try:
            if params is None:
                return ''
            return f'{prefix}{urlencode(params)}'
        except Exception:
            return ''

    @staticmethod
    def query_params(query: str = ""):
        params = parse_qs(query)
        return {key: values[0] for key, values in params.items()}

    @staticmethod
    def parse(url: str):
        href = url
        result: UrlData = {
            'href': href,
            'url': url,
            'path': "",
            'host': '',
            'query': '',
            'scheme': '',
            'origin': '',
            'params': {}
        }

        if not NHook.isvalid_str(href):
            return result
        ret = NHook.safe_func(urlparse, href, allow_fragments=False)
        if ret is None:
            return result
        parsed = dict(ret._asdict())
        result['path'] = parsed.get("path", "")
        result['scheme'] = parsed.get('scheme', "")
        result['host'] = parsed.get('netloc', "")
        result['params'] = parsed.get('params', "")
        query = parsed.get('query', "")
        origin = f"{result['scheme']}://{result['host']}" if NHook.isvalid_str(
            result['scheme']) else result['host']
        result['origin'] = origin
        result['url'] = f"{origin}{result['path']}"
        result['query'] = query
        result['params'] = NUrl.query_params(query)
        return result
