"""Validate proposed Psyon records locally. No collection or decision engine."""
import json
import re
import sys
from datetime import datetime
from pathlib import Path
from jsonschema import Draft202012Validator, FormatChecker

ROOT = Path(__file__).resolve().parent
SCHEMA = json.loads((ROOT / 'psyon_record.schema.json').read_text())
Draft202012Validator.check_schema(SCHEMA)
VALIDATOR = Draft202012Validator(SCHEMA, format_checker=FormatChecker())

def validate_record(record):
    errors = [f"{'/'.join(map(str, e.absolute_path)) or '<record>'}: {e.message}"
              for e in VALIDATOR.iter_errors(record)]
    if errors:
        return errors
    stamp = record['timestamp']
    if not re.fullmatch(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})', stamp):
        errors.append('timestamp: use an ISO date-time with seconds and an explicit timezone.')
    else:
        try:
            datetime.fromisoformat(stamp.replace('Z', '+00:00'))
        except ValueError:
            errors.append('timestamp: invalid calendar date or time.')
    ratings = list(record['core_emotions'].values())
    ratings.extend(item['rating'] for item in record['modifiers'])
    if not record['synthetic'] and any(r['basis'] == 'synthetic_example' for r in ratings):
        errors.append('A real record cannot use synthetic-example ratings.')
    if not record['synthetic'] and any(p['basis'] == 'synthetic_example' for p in record['perspectives']):
        errors.append('A real record cannot use synthetic-example perspectives.')
    return errors

def main():
    paths = [Path(p) for p in sys.argv[1:]] or [ROOT / 'synthetic_example.json', ROOT / 'blank_record.json']
    failed = False
    for path in paths:
        try:
            errors = validate_record(json.loads(path.read_text()))
        except (OSError, ValueError) as exc:
            errors = [str(exc)]
        print(f"{path.name}: {'FAIL' if errors else 'PASS'}")
        for error in errors:
            print('  ' + error)
        failed = failed or bool(errors)
    return int(failed)

if __name__ == '__main__':
    raise SystemExit(main())
