#!/usr/bin/env python3
"""Confirm your upload URL serves the archive to an anonymous client.

The evaluator fetches your link with no cookies, no account, and no browser.
A share link that shows you a preview page in your logged-in browser very often
serves that preview page -- not your zip -- to everyone else.
"""

from __future__ import annotations

import hashlib
from pathlib import Path
import sys
import urllib.request

ROOT = Path(__file__).resolve().parent.parent
ZIP = ROOT / "submission.zip"
MAX_BYTES = 120 * 1024 * 1024


def main() -> int:
    if len(sys.argv) < 2 or not sys.argv[1].strip():
        print("usage: make check-link URL=<your download url>", file=sys.stderr)
        return 2
    url = sys.argv[1].strip()
    if not url.lower().startswith("https://"):
        print(f"[FAIL] the URL must use https:// -- got {url[:40]!r}", file=sys.stderr)
        return 1

    request = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
    try:
        with urllib.request.urlopen(request, timeout=60) as response:
            content_type = (response.headers.get_content_type() or "").lower()
            body = response.read(MAX_BYTES + 1)
    except Exception as error:
        print(f"[FAIL] could not fetch the URL anonymously: {error}", file=sys.stderr)
        return 1

    if len(body) > MAX_BYTES:
        print("[FAIL] the response exceeds the 100 MB cap", file=sys.stderr)
        return 1
    if body[:4] != b"PK\x03\x04":
        print(f"[FAIL] that URL did not return a zip. Content-Type was "
              f"{content_type!r} and the response starts with {body[:16]!r}.",
              file=sys.stderr)
        print("\nThis is almost always a *share/preview* link rather than a "
              "*direct download* link. Open it in a private window: if you see "
              "a preview page instead of a download, the evaluator sees that "
              "page too.", file=sys.stderr)
        return 1

    digest = hashlib.sha256(body).hexdigest()
    print(f"[OK] the URL returns a zip anonymously ({len(body):,} bytes)")
    print(f"[OK] SHA-256 of what the evaluator will download:\n  {digest}")
    if ZIP.is_file():
        local = hashlib.sha256(ZIP.read_bytes()).hexdigest()
        if local != digest:
            print("\n[FAIL] that does NOT match your local submission.zip:",
                  file=sys.stderr)
            print(f"  local:  {local}", file=sys.stderr)
            print("You uploaded a different file, or an older build.", file=sys.stderr)
            return 1
        print("[OK] matches your local submission.zip exactly.")
    print("\nPaste the SHA-256 above into the Results Form.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
