"""Offline URL-construction fixture. No network requests or credentials.

Run: python3 agent-url-construction.py [--test]
This restrictive document-ID contract is application policy, not an SSRF filter.
"""
import json
import re
import sys
import unittest
from urllib.parse import urljoin, urlsplit, urlunsplit

ORIGIN = "https://docs.example"
BASE = ORIGIN + "/v1/documents/"
DOCUMENT_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}", re.ASCII)


def require_origin(url):
    """Check the complete constructed URL against one fixed origin policy."""
    if not isinstance(url, str) or any(ord(c) <= 32 or ord(c) == 127 for c in url):
        raise ValueError("invalid URL text")
    parts = urlsplit(url)
    if (parts.scheme != "https" or parts.hostname != "docs.example"
            or parts.port not in (None, 443)
            or parts.username is not None or parts.password is not None
            or parts.fragment):
        raise ValueError("destination outside policy")
    return url


def document_url(document_id):
    """Accept an opaque ID, never a caller-selected path or URL."""
    if not isinstance(document_id, str) or not DOCUMENT_ID.fullmatch(document_id):
        raise ValueError("invalid document ID")
    result = urlunsplit(("https", "docs.example", "/v1/documents/" + document_id, "", ""))
    return require_origin(result)


def demo():
    supplied = "//other.example/collect"
    require_origin(BASE)
    candidate = urljoin(BASE, supplied)
    try:
        require_origin(candidate)
        decision = "allow"
    except ValueError:
        decision = "deny"
    return {"base_check": "allow", "joined_url": candidate,
            "final_origin_check": decision,
            "constructed_document_url": document_url("doc_42")}


class URLTests(unittest.TestCase):
    def test_base_check_does_not_constrain_join(self):
        self.assertEqual(require_origin(BASE), BASE)
        self.assertEqual(urljoin(BASE, "//other.example/collect"), "https://other.example/collect")

    def test_absolute_url_replaces_base(self):
        self.assertEqual(urljoin(BASE, "https://other.example/x"), "https://other.example/x")

    def test_final_origin_rejects_other_host(self):
        with self.assertRaises(ValueError):
            require_origin(urljoin(BASE, "//other.example/collect"))

    def test_same_origin_is_not_path_authorisation(self):
        candidate = urljoin(BASE, "/admin/export")
        self.assertEqual(require_origin(candidate), ORIGIN + "/admin/export")
        with self.assertRaises(ValueError):
            document_url("/admin/export")

    def test_valid_ids(self):
        for value in ["a", "doc_42", "A-9", "a" * 64]:
            with self.subTest(value=value):
                self.assertEqual(document_url(value), BASE + value)

    def test_invalid_ids(self):
        for value in ["", "a" * 65, ".", "..", "../admin", "/admin", "//other.example",
                      "https://other.example/x", "a?x=1", "a#x", "a%2fb", "a\\b",
                      "a\nb", " a", "é", None, True, 42]:
            with self.subTest(value=value):
                with self.assertRaises(ValueError):
                    document_url(value)

    def test_origin_policy(self):
        for url in ["http://docs.example/x", "https://docs.example.other.example/x",
                    "https://docs.example@other.example/x", "https://user@docs.example/x",
                    "https://docs.example:444/x", "https://docs.example:bad/x",
                    "https://docs.example/x#fragment", " https://docs.example/x",
                    "https://docs.example/\nx"]:
            with self.subTest(url=url):
                with self.assertRaises(ValueError):
                    require_origin(url)
        self.assertEqual(require_origin("https://docs.example:443/x"), "https://docs.example:443/x")

    def test_demo(self):
        self.assertEqual(demo()["final_origin_check"], "deny")
        self.assertEqual(demo()["constructed_document_url"], BASE + "doc_42")


if __name__ == "__main__":
    if sys.argv[1:] == ["--test"]:
        unittest.main(argv=[sys.argv[0]])
    elif not sys.argv[1:]:
        print(json.dumps(demo(), indent=2))
    else:
        raise SystemExit("Usage: agent-url-construction.py [--test]")
