#!/usr/bin/env python3
"""Offline synthetic GET redirect-target checks. No fetching or credential reads."""
from urllib.parse import urljoin, urlsplit, urlunsplit


class Hold(ValueError):
    pass


def normalize(url):
    # Deliberately narrow demonstration inputs; this is not a security URL parser.
    if not isinstance(url, str) or not url or any(ord(c) <= 32 for c in url) or '\\' in url:
        raise Hold('MALFORMED_LOCATION')
    try:
        parts = urlsplit(url)
        host, port = parts.hostname, parts.port
    except ValueError:
        raise Hold('MALFORMED_LOCATION')
    if parts.username is not None or parts.password is not None:
        raise Hold('CREDENTIAL_IN_LOCATION')
    if parts.scheme.lower() != 'https':
        raise Hold('SCHEME')
    if not host:
        raise Hold('MALFORMED_LOCATION')
    # Do not guess whether a query contains secrets: this fixture holds every query.
    if parts.query or '?' in url.split('#', 1)[0]:
        raise Hold('QUERY_REVIEW')
    port = 443 if port is None else port
    authority = host.lower() + ((':' + str(port)) if port != 443 else '')
    target = urlunsplit(('https', authority, parts.path or '/', '', ''))
    return target, ('https', host.lower(), port)


def admit(start, locations, approved_origins, max_hops=2, method='GET'):
    """Return target-only outcome, redacted/normalized target, evaluated hops."""
    if method != 'GET':
        return 'HOLD_METHOD', '[withheld]', 0
    if isinstance(max_hops, bool) or not isinstance(max_hops, int) or max_hops < 0:
        raise ValueError('max_hops must be a nonnegative integer')
    try:
        current, current_origin = normalize(start)
    except Hold as e:
        return 'HOLD_START_' + str(e), '[withheld]', 0
    if current_origin not in approved_origins:
        return 'HOLD_START_UNAPPROVED', '[withheld]', 0
    if not isinstance(locations, list) or not locations:
        return 'HOLD_NO_REDIRECT_EVIDENCE', '[withheld]', 0
    seen = {current}
    for hop, location in enumerate(locations, start=1):
        if hop > max_hops:
            return 'HOLD_HOP_LIMIT', '[withheld]', hop - 1
        if location is None or location == '':
            return 'HOLD_MISSING_LOCATION', '[withheld]', hop
        if not isinstance(location, str) or any(ord(c) <= 32 for c in location) or '\\' in location:
            return 'HOLD_MALFORMED_LOCATION', '[withheld]', hop
        try:
            target, target_origin = normalize(urljoin(current, location))
        except (Hold, ValueError) as e:
            reason = str(e) if isinstance(e, Hold) else 'MALFORMED_LOCATION'
            return 'HOLD_' + reason, '[withheld]', hop
        if target_origin not in approved_origins:
            return 'HOLD_TARGET_UNAPPROVED', '[withheld]', hop
        if target in seen:
            return 'HOLD_CYCLE', '[withheld]', hop
        seen.add(target)
        current = target
    return 'TARGET_ONLY_ACCEPTED', current, len(locations)


def main():
    approved = {('https', 'app.example.test', 443), ('https', 'login.example.test', 443)}
    start = 'https://app.example.test/a'
    cases = [
        ('relative', start, ['/reports/2026'], 2, 'GET', 'TARGET_ONLY_ACCEPTED'),
        ('listed_cross_origin', start, ['https://login.example.test/continue'], 2, 'GET', 'TARGET_ONLY_ACCEPTED'),
        ('explicit_default_port', start, ['https://app.example.test:443/report'], 2, 'GET', 'TARGET_ONLY_ACCEPTED'),
        ('unapproved_host', start, ['https://elsewhere.example.test/x'], 2, 'GET', 'HOLD_TARGET_UNAPPROVED'),
        ('downgrade', start, ['http://app.example.test/x'], 2, 'GET', 'HOLD_SCHEME'),
        ('location_userinfo', start, ['https://fictional:example@app.example.test/x'], 2, 'GET', 'HOLD_CREDENTIAL_IN_LOCATION'),
        ('query_needs_review', start, ['/report?example_token=fictional'], 2, 'GET', 'HOLD_QUERY_REVIEW'),
        ('malformed_port', start, ['https://app.example.test:bad/x'], 2, 'GET', 'HOLD_MALFORMED_LOCATION'),
        ('cycle', start, ['/b', '/a'], 2, 'GET', 'HOLD_CYCLE'),
        ('hop_limit', start, ['/b', '/c', '/d'], 2, 'GET', 'HOLD_HOP_LIMIT'),
        ('missing_location', start, [''], 2, 'GET', 'HOLD_MISSING_LOCATION'),
        ('unapproved_start', 'https://elsewhere.example.test/a', ['/b'], 2, 'GET', 'HOLD_START_UNAPPROVED'),
        ('empty_chain', start, [], 2, 'GET', 'HOLD_NO_REDIRECT_EVIDENCE'),
        ('non_get', start, ['/b'], 2, 'POST', 'HOLD_METHOD'),
    ]
    accepted = 0
    print('offline_synthetic_proxy_redirect_admission')
    print('network_requests=0 credential_reads=0 method=GET target_checks_only')
    for name, initial, locations, cap, method, expected in cases:
        decision, target, hops = admit(initial, locations, approved, cap, method)
        assert decision == expected, (name, decision, expected)
        accepted += decision == 'TARGET_ONLY_ACCEPTED'
        # Print case aliases and decisions only, never raw Location, userinfo or queries.
        print('%s=%s evaluated_hops=%d' % (name, decision, hops))
    assert admit(start, ['/reports/2026'], approved)[1] == 'https://app.example.test/reports/2026'
    assert normalize('https://app.example.test:443/report') == normalize('https://app.example.test/report')
    print('summary=TARGET_ONLY_ACCEPTED:%d HOLD:%d total:%d' % (accepted, len(cases) - accepted, len(cases)))
    print('limits=no_auth_cookie_route_dns_tls_permission_or_provider_verification')


if __name__ == '__main__':
    main()
