import requests
import json

domains = [
    "qdrant-b3knu-u50607.a.elestio.app",
    "redis-genesis-u50607.a.elestio.app",
    "postgresql-genesis-u50607.a.elestio.app"
]

print("Resolving via DoH...")
results = {}

for d in domains:
    try:
        # Use Google DoH
        resp = requests.get(f"https://dns.google/resolve?name={d}", timeout=10)
        data = resp.json()
        if "Answer" in data:
            # Get last A record
            ip = [r['data'] for r in data['Answer'] if r['type'] == 1][-1]
            results[d] = ip
            print(f"{d} -> {ip}")
        else:
            print(f"{d} -> NO ANSWER")
    except Exception as e:
        print(f"{d} -> ERROR: {e}")

# Update config if successful
try:
    with open("genesis_config.json", "r") as f:
        config = json.load(f)
    
    updates = 0
    if "qdrant-b3knu-u50607.a.elestio.app" in results:
        config["qdrant"]["host"] = results["qdrant-b3knu-u50607.a.elestio.app"]
        updates += 1
    if "redis-genesis-u50607.a.elestio.app" in results:
        config["redis"]["host"] = results["redis-genesis-u50607.a.elestio.app"]
        updates += 1
    if "postgresql-genesis-u50607.a.elestio.app" in results:
        config["postgres"]["host"] = results["postgresql-genesis-u50607.a.elestio.app"]
        updates += 1

    if updates > 0:
        with open("genesis_config.json", "w") as f:
            json.dump(config, f, indent=2)
        print(f"Updated genesis_config.json with {updates} IPs")
except Exception as e:
    print(f"Config update failed: {e}")
