"""No-network supplied-record exercise, not XML or Google behaviour validation."""
import datetime as dt
import json
import sys
from urllib.parse import urlsplit


def instant(value):
    if not isinstance(value, str) or 'T' not in value:
        raise ValueError('Exercise requires an aware datetime, not date-only lastmod')
    try:
        parsed = dt.datetime.fromisoformat(value.replace('Z', '+00:00'))
    except ValueError as exc:
        raise ValueError('Invalid exercise datetime') from exc
    if parsed.tzinfo is None or parsed.utcoffset() is None:
        raise ValueError('Timezone required')
    return parsed.astimezone(dt.timezone.utc)


def review(rows):
    if not isinstance(rows, list) or not rows:
        raise ValueError('Nonempty case list required')
    seen = set()
    output = []
    for row in rows:
        if not isinstance(row, dict):
            raise ValueError('Each case must be an object')
        identity = row.get('case')
        if not isinstance(identity, str) or not identity.strip() or identity in seen:
            raise ValueError('Unique nonempty case IDs required')
        seen.add(identity)
        url = row.get('url')
        if not isinstance(url, str):
            raise ValueError('URL string required')
        parsed = urlsplit(url)
        if parsed.scheme != 'https' or not parsed.netloc or parsed.username or parsed.password or parsed.fragment or any(c.isspace() for c in url):
            raise ValueError('Exercise requires absolute HTTPS URL without credentials/fragment')
        kind = row.get('changeKind')
        if kind not in {'main-content', 'structured-data', 'links', 'copyright-only', 'build-only', 'unknown'}:
            raise ValueError('Unknown change category')
        changed = instant(row.get('changeAt'))
        declared = instant(row.get('declaredLastmod'))
        ref = row.get('evidenceRef')
        if kind in {'copyright-only', 'build-only'}:
            verdict = 'not-proof-of-page-change'
        elif kind == 'unknown' or not isinstance(ref, str) or not ref.strip():
            verdict = 'evidence-needed'
        elif changed != declared:
            verdict = 'timestamp-review'
        else:
            verdict = 'supplied-records-consistent'
        output.append({'case': identity, 'url': url, 'verdict': verdict,
                       'sourceAuthenticityVerified': None,
                       'googleCrawlConfirmed': None, 'indexConfirmed': None})
    return output


if __name__ == '__main__':
    if len(sys.argv) != 2:
        raise SystemExit('Usage: python3 check.py filled-examples.json')
    with open(sys.argv[1], encoding='utf-8') as source:
        result = review(json.load(source))
    print(json.dumps(result, ensure_ascii=False, indent=2))
