"""Compare supplied log IPs and supplied CIDR snapshots. Never fetch or authenticate."""
import datetime as dt
import ipaddress
import json
import re
import sys
from urllib.parse import urlsplit

ROLES = {'OAI-SearchBot': 'search', 'GPTBot': 'training', 'ChatGPT-User': 'user_requested'}


def instant(value):
    if not isinstance(value, str):
        raise ValueError('A timestamp with explicit offset is required')
    try:
        date = dt.datetime.fromisoformat(value.replace('Z', '+00:00'))
    except ValueError:
        raise ValueError('Invalid timestamp') from None
    if date.tzinfo is None:
        raise ValueError('Timezone offset is required')
    return date


def compare(record, snapshots):
    if not isinstance(record, dict) or not isinstance(record.get('id'), str) or not record['id']:
        raise ValueError('Nonempty record id required')
    url = record.get('url')
    if not isinstance(url,str) or any(c.isspace() for c in url):
        raise ValueError('Exact HTTP(S) request URL required')
    try:
        parsed = urlsplit(url)
        port = parsed.port
    except ValueError:
        raise ValueError('Malformed request URL') from None
    if parsed.scheme not in {'http','https'} or not parsed.hostname or parsed.username or parsed.password or parsed.fragment:
        raise ValueError('Request URL must be HTTP(S), without credentials or fragment')
    ua = record.get('userAgent')
    if not isinstance(ua, str):
        raise ValueError('userAgent string required')
    if not isinstance(snapshots, dict):
        raise ValueError('snapshots object required')
    if record.get('remoteIp') is not None and not isinstance(record['remoteIp'], str):
        raise ValueError('remoteIp must be a string or null')
    observed = instant(record.get('observedAt'))
    agents = [a for a in ROLES if re.search(r'(?<![\w-])'+re.escape(a)+r'(?:/[\d.]+)?(?![\w-])', ua)]
    agent = agents[0] if len(agents) == 1 else None
    identity = 'UNKNOWN_AGENT' if not agents else 'AMBIGUOUS_AGENT' if len(agents)>1 else 'MISSING_SNAPSHOT'
    age = None
    if agent and agent in snapshots:
        s = snapshots[agent]
        if not isinstance(s, dict) or not isinstance(s.get('sourceRef'), str) or not s['sourceRef']:
            raise ValueError('Snapshot sourceRef required')
        captured = instant(s.get('capturedAt'))
        networks = s.get('cidrs')
        if not isinstance(networks, list) or any(not isinstance(n,str) for n in networks):
            raise ValueError('cidrs must be an array of strings')
        nets = [ipaddress.ip_network(n, strict=True) for n in networks]
        age = int((observed-captured).total_seconds())
        ip = record.get('remoteIp')
        if age < 0:
            identity = 'SNAPSHOT_CAPTURED_AFTER_REQUEST'
        elif not nets:
            identity = 'EMPTY_SUPPLIED_SET'
        elif ip is None:
            identity = 'MISSING_REMOTE_IP'
        else:
            try:
                addr = ipaddress.ip_address(ip)
            except ValueError:
                raise ValueError('Invalid remoteIp') from None
            identity = 'MATCH_SUPPLIED_SET' if any(addr.version==n.version and addr in n for n in nets) else 'NO_MATCH_SUPPLIED_SET'
    status = record.get('status')
    if status is not None and (type(status) is not int or not 100 <= status <= 599):
        raise ValueError('status must be HTTP100..599 or null')
    body = record.get('bodyClass')
    if body not in {'article', 'challenge', 'empty', 'unknown'}:
        raise ValueError('bodyClass must be article/challenge/empty/unknown')
    content = 'UNKNOWN_RESPONSE' if status is None else 'CHALLENGE_RECORDED' if body=='challenge' else 'CONTENT_RECORDED' if status==200 and body=='article' else 'NON_CONTENT_RESPONSE'
    return {'id': record['id'], 'requestUrl': url, 'claimedAgent': agent, 'documentedRoleForClaimedAgent': ROLES.get(agent),
            'ipComparison': identity, 'snapshotAgeSecondsAtRequest': age,
            'recordedResponse': content, 'realCrawlerIdentity': None,
            'actualAiCitation': None,
            'limit': 'Supplied-record arithmetic only. Source integrity, log authenticity, request identity and original AI answer require independent evidence.'}


def run(data):
    if not isinstance(data, dict) or not isinstance(data.get('snapshots'),dict) or not isinstance(data.get('requests'),list):
        raise ValueError('snapshots object and requests array required')
    results = [compare(r,data['snapshots']) for r in data['requests']]
    ids = [r['id'] for r in results]
    if len(set(ids)) != len(ids):
        raise ValueError('Duplicate request ids')
    return results


if __name__ == '__main__':
    try:
        with open(sys.argv[1],encoding='utf-8') as f:
            print(json.dumps(run(json.load(f)),ensure_ascii=False,indent=2))
    except (ValueError,IndexError,OSError) as e:
        print(json.dumps({'error':str(e)}),file=sys.stderr)
        sys.exit(2)
