#!/usr/bin/env python3
import sys
import json
import os

with open('./human.json', 'r') as f:
    content = json.load(f)

if os.environ['REMOTE_ADDR'] == os.environ['SERVER_ADDR']:

    host = os.environ.get('HTTP_X_FORWARDED_HOST', os.environ['HTTP_HOST'])
    host = f'https://{host}'

    with open('hosts.json', 'r') as f:
        all_hosts = json.load(f)

    if host not in all_hosts:
        all_hosts.append(host)
        with open('hosts.json', 'w+') as f:
            json.dump(all_hosts, f)

    all_hosts = {*all_hosts}
    vouched_hosts = {item['url']: item['vouched_at'] for item in content['vouches']}
    host_keys = set(vouched_hosts.keys())
    result = (host_keys | all_hosts) - {host}

    content['url'] = host
    content['vouches'] = [
        {'url': item, 'vouched_at': vouched_hosts.get(item, '2026-03-25')}
        for item in result
    ]
    encoded = json.dumps(content)
    sys.stdout.write('Content-Type: application/json\n')
    sys.stdout.write(f'Content-Length: {len(encoded)}\n\n')
    sys.stdout.write(encoded)
else:
    encoded = json.dumps({'detail': 'invalid host'})
    sys.stdout.write('Status: 403')
    sys.stdout.write('Content-Type: application/json\n')
    sys.stdout.write(f'Content-Length: {len(encoded)}\n\n')
    sys.stdout.write(encoded)
