import pathlib
import sys
import urllib.parse
import urllib.request


BASE = "https://www.xinje.com"


def request(url: str) -> urllib.request.Request:
    return urllib.request.Request(
        url,
        headers={
            "User-Agent": "Mozilla/5.0 (Codex Xinje download)",
            "Referer": f"{BASE}/web/downloadCenter/index",
            "X-Requested-With": "XMLHttpRequest",
        },
    )


def quote_url(url: str) -> str:
    parts = urllib.parse.urlsplit(url)
    path = urllib.parse.quote(parts.path, safe="/%")
    query = urllib.parse.quote(parts.query, safe="=&%")
    return urllib.parse.urlunsplit((parts.scheme, parts.netloc, path, query, parts.fragment))


def resolve_source(source: str) -> str:
    if source.isdigit():
        req = request(f"{BASE}/web/file-download/down/{source}")
        with urllib.request.urlopen(req, timeout=30) as response:
            signed_url = response.read().decode("utf-8", "ignore").strip()
        # The site may return a signed OSS URL. In some environments CDN auth
        # conflicts with query-string signatures, so direct catalog URLs may be
        # more reliable. Keep the signed URL untouched when using file IDs.
        return signed_url
    return quote_url(source)


def main() -> None:
    if len(sys.argv) != 3:
        raise SystemExit("usage: download_xinje_file.py <url-or-file-id> <output-path>")
    url = resolve_source(sys.argv[1])
    output = pathlib.Path(sys.argv[2])
    output.parent.mkdir(parents=True, exist_ok=True)
    with urllib.request.urlopen(request(url), timeout=120) as response:
        output.write_bytes(response.read())
    print(f"downloaded {output} ({output.stat().st_size} bytes)")


if __name__ == "__main__":
    main()
