"""Synthetic offline evidence-pair review; no network or GSC access."""
import json
import sys
from datetime import datetime
from urllib.parse import urlsplit


def timestamp(value):
    if not isinstance(value, str):
        raise ValueError('Timestamp must be text')
    try:
        result = datetime.fromisoformat(value.replace('Z', '+00:00'))
    except ValueError as exc:
        raise ValueError('Invalid timestamp') from exc
    if result.tzinfo is None:
        raise ValueError('Explicit timezone required')
    return result


def url(value):
    if not isinstance(value, str) or any(c.isspace() for c in value):
        raise ValueError('URL must be whitespace-free text')
    p = urlsplit(value)
    if p.scheme not in ('http', 'https') or not p.netloc or p.username or p.password or p.fragment:
        raise ValueError('Absolute HTTP(S) URL without credentials or fragment required')
    return value


def compare(item):
    ident = item.get('id')
    if not isinstance(ident, str) or not ident.strip():
        raise ValueError('Non-empty case ID required')
    before, live = item.get('indexed'), item.get('live')
    if not isinstance(before, dict) or not isinstance(live, dict):
        raise ValueError('Two explicit evidence records required')
    for row, mode, statuses in [(before, 'indexed', {'soft404', 'indexed', 'excluded', 'unknown'}),
                                (live, 'live', {'available', 'unavailable', 'unknown'})]:
        if row.get('mode') != mode or row.get('status') not in statuses:
            raise ValueError('Evidence mode/status mismatch')
        url(row['requestedURL'])
        if row.get('effectiveURL') is not None:
            url(row['effectiveURL'])
        if row.get('evidenceAt') is not None:
            timestamp(row['evidenceAt'])
        if row.get('sourceRef') is not None and not isinstance(row['sourceRef'], str):
            raise ValueError('Source reference must be text or null')
    if before['requestedURL'] != live['requestedURL']:
        verdict = 'INCOMPARABLE_REQUESTED_URLS'
    elif any(row.get('effectiveURL') is None for row in (before, live)):
        verdict = 'INCOMPLETE_TARGET_IDENTITY'
    elif before['effectiveURL'] != live['effectiveURL']:
        verdict = 'INCOMPARABLE_EFFECTIVE_URLS'
    elif any(not row.get('sourceRef', '').strip() if isinstance(row.get('sourceRef'), str)
             else True for row in (before, live)) or any(row.get('evidenceAt') is None for row in (before, live)):
        verdict = 'INCOMPLETE_SOURCE_RECORD'
    elif timestamp(live['evidenceAt']) <= timestamp(before['evidenceAt']):
        verdict = 'NON_ADVANCING_EVIDENCE_TIME'
    elif live['status'] == 'unavailable':
        verdict = 'LATER_LIVE_ACCESS_FAILURE_RECORDED'
    elif 'unknown' in (before['status'], live['status']):
        verdict = 'SUPPLIED_STATUS_UNKNOWN'
    else:
        verdict = 'DATED_PAIR_READY_FOR_HUMAN_VERSION_REVIEW'
    return {'id': ident, 'verdict': verdict,
            'indexedStatusSupplied': before['status'], 'liveStatusSupplied': live['status'],
            'indexingRecoveryConfirmed': None, 'googleCanonicalChoiceConfirmed': None,
            'causeOfSoft404': None,
            'limit': 'Supplied synthetic records only; validates neither account data nor content completeness. No live result proves an indexing update.'}


def run(records):
    if not isinstance(records, list) or not records:
        raise ValueError('Non-empty case list required')
    outputs = [compare(row) for row in records]
    if len({x['id'] for x in outputs}) != len(outputs):
        raise ValueError('Duplicate case ID')
    return outputs


if __name__ == '__main__':
    with open(sys.argv[1]) as handle:
        print(json.dumps(run(json.load(handle)), ensure_ascii=False, indent=2))
