#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import requests
import json

PYTHON_API = "http://localhost:5005"

def test():
    print("=" * 60)
    print("Test Proxy IP and Location")
    print("=" * 60)

    # Test proxy
    print("\n[1] Getting proxy IP...")
    proxy_data = {
        "provider": "shenlong",
        "productKey": "o2ihwv3e",
        "signature": "ccff437b0c211d7a758b0926cbdcf958",
        "regionCode": "310000",
        "city": "Shanghai",
        "platform": "weixin"
    }

    try:
        resp = requests.post(f"{PYTHON_API}/proxy/test", json=proxy_data, timeout=30)
        result = resp.json()
        print(f"Response: {json.dumps(result, indent=2, ensure_ascii=False)}")

        if result.get("success"):
            proxy = result.get("proxy", "")
            print(f"\n[OK] Proxy: {proxy}")

            # Extract IP
            proxy_ip = proxy.replace("http://", "").split(":")[0]
            print(f"Proxy IP: {proxy_ip}")

            # Query IP location
            print(f"\n[2] Querying IP location...")
            try:
                ip_info = requests.get(f"http://ip-api.com/json/{proxy_ip}?lang=zh-CN", timeout=5).json()
                print(f"Country: {ip_info.get('country', 'N/A')}")
                print(f"Region: {ip_info.get('regionName', 'N/A')}")
                print(f"City: {ip_info.get('city', 'N/A')}")
                print(f"ISP: {ip_info.get('isp', 'N/A')}")

                city = ip_info.get('city', '')
                if 'shanghai' in city.lower() or 'shang hai' in city.lower() or city == '上海':
                    print(f"\n[OK] Proxy location is Shanghai")
                else:
                    print(f"\n[WARNING] Proxy location is {city}, NOT Shanghai!")
                    print("This is why WeChat shows wrong location")
            except Exception as e:
                print(f"[ERROR] IP query failed: {e}")
        else:
            print(f"[ERROR] Proxy failed: {result.get('error', 'Unknown')}")

    except Exception as e:
        print(f"[ERROR] Request failed: {e}")

    print("\n" + "=" * 60)

if __name__ == "__main__":
    test()
