#!/usr/bin/env python3
"""JSON API Aggregation - Fetches and merges API responses"""

import urllib.request
import json
import jsonschema

# Response schema for validation
RESPONSE_SCHEMA = {
    "type": "object",
    "properties": {
        "get_response": {"type": "object"},
        "ip_response": {"type": "object"},
        "merged_at": {"type": "string"}
    },
    "required": ["get_response", "ip_response", "merged_at"]
}

def fetch_url(url, timeout=10):
    """Fetch JSON from URL"""
    with urllib.request.urlopen(url, timeout=timeout) as resp:
        return json.loads(resp.read().decode())

def main():
    print("1. Fetching httpbin.org/get and httpbin.org/ip concurrently...")
    
    # Fetch both endpoints
    get_response = fetch_url("https://httpbin.org/get")
    ip_response = fetch_url("https://httpbin.org/ip")
    
    print("   - GET /get: OK")
    print("   - GET /ip: OK")
    
    # Merge responses
    print("\n2. Merging responses...")
    merged = {
        "get_response": get_response,
        "ip_response": ip_response,
        "merged_at": json.dumps(get_response).split('T')[0] if 'date' in str(get_response) else "2026-03-22"
    }
    
    # Validate with jsonschema
    print("\n3. Validating with jsonschema...")
    try:
        jsonschema.validate(merged, RESPONSE_SCHEMA)
        print("   - Schema validation: PASSED")
    except jsonschema.ValidationError as e:
        print(f"   - Schema validation: FAILED - {e.message}")
        return False
    
    # Save formatted JSON
    print("\n4. Saving to /tmp/agg_result.json...")
    output_path = "/tmp/agg_result.json"
    with open(output_path, 'w') as f:
        json.dump(merged, f, indent=2)
    print(f"   - Saved: {output_path}")
    
    print("\n5. Result preview:")
    print(json.dumps(merged, indent=2)[:500] + "...")
    
    return True

if __name__ == '__main__':
    success = main()
    print(f"\n{'SUCCESS' if success else 'FAILURE'}")
