#!/usr/bin/env python3
"""Offline handoff completeness check; not security enforcement or authorization.

Reads one UTF-8 JSON file. No network, command execution, or file writes.
Exit 0: complete; 1: incomplete/invalid fields; 2: input/usage error.
"""
import json
import sys
from datetime import datetime
from pathlib import Path
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError


def validate(data):
    if not isinstance(data, dict):
        return ['handoff: expected a JSON object']
    errors = []
    required = ('owner', 'outcome', 'scope', 'acceptance_criteria', 'deadline',
                'timezone', 'dependencies', 'approval_status', 'next_action')
    for key in required:
        if key not in data:
            errors.append(key + ': required field missing')
            continue
        value = data[key]
        if key in ('scope', 'acceptance_criteria', 'dependencies'):
            good = (isinstance(value, list)
                    and all(isinstance(v, str) and v.strip() for v in value)
                    and (key == 'dependencies' or bool(value)))
            if not good:
                errors.append(key + ': expected a list of nonempty strings; scope and criteria cannot be empty')
        elif key == 'deadline':
            if value is not None:
                try:
                    if not isinstance(value, str):
                        raise ValueError
                    parsed = datetime.fromisoformat(value)
                    if parsed.tzinfo is None:
                        raise ValueError
                except ValueError:
                    errors.append('deadline: use null (not agreed) or an ISO timestamp with UTC offset')
        elif key == 'timezone':
            try:
                if not isinstance(value, str) or not value.strip():
                    raise ValueError
                # UTC needs no external IANA database; named regions still do.
                if value != 'UTC':
                    ZoneInfo(value)
            except (ValueError, ZoneInfoNotFoundError):
                errors.append('timezone: expected an available IANA zone such as UTC')
        elif key == 'approval_status':
            if value not in ('not_requested', 'pending', 'approved', 'rejected'):
                errors.append('approval_status: use not_requested, pending, approved, or rejected')
        elif not isinstance(value, str) or not value.strip():
            errors.append(key + ': expected nonempty text')
    return errors


def main():
    if len(sys.argv) != 2:
        print('Usage: python3 validate_handoff.py handoff.json', file=sys.stderr)
        return 2
    try:
        data = json.loads(Path(sys.argv[1]).read_text(encoding='utf-8'))
    except (OSError, ValueError) as exc:
        print('Input error: cannot read UTF-8 JSON (' + type(exc).__name__ + ')', file=sys.stderr)
        return 2
    errors = validate(data)
    if errors:
        print('Completeness check failed:\n' + '\n'.join('- ' + e for e in errors), file=sys.stderr)
        return 1
    print('Completeness check passed; not authorization. Human review is still required.')
    return 0


if __name__ == '__main__':
    sys.exit(main())
