#!/usr/bin/env python3
"""
Proxy checker - validates proxy and returns IP, country, timezone, latency.
"""

import sys
import json
import time

def main():
    if len(sys.argv) < 2:
        print(json.dumps({"success": False, "error": "Missing proxy config JSON"}))
        sys.exit(1)

    try:
        config = json.loads(sys.argv[1])
    except json.JSONDecodeError as e:
        print(json.dumps({"success": False, "error": f"Invalid JSON: {e}"}))
        sys.exit(1)

    host = config.get("host", "")
    port = config.get("port", config.get("int", 8080))
    ptype = config.get("type", "http")
    user = config.get("username", "")
    pwd = config.get("password", "")

    if not host or not port:
        print(json.dumps({"success": False, "error": "Missing host or port"}))
        sys.exit(1)

    try:
        from camoufox.sync_api import Camoufox
    except ImportError:
        print(json.dumps({
            "success": False,
            "error": "Camoufox not installed. Run: pip install -U camoufox[geoip]"
        }))
        sys.exit(1)

    auth = f"{user}:{pwd}@" if user or pwd else ""
    proxy_url = f"{ptype}://{auth}{host}:{port}"

    start = time.time()
    try:
        with Camoufox(
            headless=True,
            proxy={"server": proxy_url},
            geoip=True,
        ) as browser:
            page = browser.new_page()
            page.goto("https://api.ipify.org?format=json", wait_until="domcontentloaded", timeout=15000)
            content = page.content()
            page.close()
    except Exception as e:
        elapsed = int((time.time() - start) * 1000)
        print(json.dumps({
            "success": False,
            "error": str(e),
            "latency": elapsed,
        }))
        sys.exit(1)

    latency = int((time.time() - start) * 1000)

    try:
        import re
        ip_match = re.search(r'"ip"\s*:\s*"([^"]+)"', content)
        ip = ip_match.group(1) if ip_match else None
    except Exception:
        ip = None

    country = None
    timezone_suggestion = None

    if ip:
        try:
            import urllib.request
            with urllib.request.urlopen(
                f"http://ip-api.com/json/{ip}?fields=countryCode,timezone",
                timeout=5
            ) as r:
                data = json.loads(r.read().decode())
                country = data.get("countryCode")
                timezone_suggestion = data.get("timezone")
        except Exception:
            pass

    result = {
        "success": True,
        "ip": ip,
        "country": country,
        "timezone": timezone_suggestion,
        "latency": latency,
    }
    print(json.dumps(result))


if __name__ == "__main__":
    main()
