#!/usr/bin/env python3
"""Python 3.10+: free key check by default; --email performs one paid check."""
import argparse
import json
import os
import sys
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen


def request(api_key, email=None):
    path = '/api-keys/me' if email is None else '/validate'
    body = None if email is None else json.dumps({'email': email}).encode()
    req = Request('https://api.validatedmails.com' + path, data=body,
                  headers={'Authorization': 'Bearer ' + api_key, 'Content-Type': 'application/json'})
    # Never automatically retry: a lost response may follow a charge.
    with urlopen(req, timeout=60) as response:
        result = json.load(response)
    if not isinstance(result, dict) or (email is None and result.get('ok') is not True) or (email is not None and result.get('status') not in ('valid', 'risky', 'invalid', 'unknown')):
        raise ValueError('Unexpected API response')
    return result


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--email', help='An address you are authorized to verify; may consume 1 credit')
    args = parser.parse_args()
    key = os.environ.get('VALIDATEDMAILS_API_KEY', '').strip()
    if not key:
        print('Set VALIDATEDMAILS_API_KEY in your environment.', file=sys.stderr)
        return 1
    try:
        result = request(key, args.email)
        if args.email is None:
            print('API connection verified. No validation credits used.')
        else:
            print(json.dumps({k: result.get(k) for k in ('status', 'score', 'reason', 'trace_id')}, indent=2))
        return 0
    except HTTPError as exc:
        print('API request failed (HTTP %s). Check authentication (401), credits (402), or capacity (429). No automatic retry was made.' % exc.code, file=sys.stderr)
    except (URLError, TimeoutError, ValueError):
        print('Result not confirmed. A validation may have completed and used a credit. Check account activity before repeating. No automatic retry was made.', file=sys.stderr)
    return 1


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