package main

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	"time"
)

type IPInfo struct {
	Msg  string `json:"msg"`
	Data struct {
		Continent string `json:"continent"`
		Country   string `json:"country"`
	} `json:"data"`
}

func isValidIP(ip string) bool {
	return net.ParseIP(ip) != nil
}

func curl_(ip string) (string, error) {

	var err error
	var url string

	if !isValidIP(ip) {
		log.Printf("无效的 IP 地址: %s", ip)
	}

	// 目标 URL
	url = "https://qifu.baidu.com/ip/geo/v1/district?ip=" + ip

	// 创建 HTTP 请求
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Printf("创建请求时出错: %v", err)
	}

	// 设置请求头
	req.Header.Set("User-Agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Mobile Safari/537.36")
	req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
	req.Header.Set("Accept-Encoding", "gzip, deflate, br, zstd")
	req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
	req.Header.Set("Cache-Control", "max-age=0")
	req.Header.Set("Connection", "keep-alive")
	req.Header.Set("Cookie", "BIDUPSID=04922F7E0DDC6A5B7E0BA15C33FD2176; PSTM=1722408897; BAIDUID=8313999060289847CAE0A6F34A9C4206:FG=1; Hm_lvt_edc762f9f8f5f525fad4770a32b5edda=1724987641; Hm_lvt_28a17f66627d87f1d046eae152a1c93d=1724987645; AGL_USER_ID=186badbd-dd36-4d39-89f4-8d2aa7a01414; BDUSS=1pvWmdhYThIelRSS1NuQkJESHNYV0REcG9teXMxOW9VaURTU2tyRlZTZ3Z4dmhtRVFBQUFBJCQAAAAAAAAAAAEAAADGRkRexaPT8cHrAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC850WYvOdFmM")
	req.Header.Set("Host", "qifu.baidu.com")
	req.Header.Set("Sec-Ch-Ua", `"Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"`)
	req.Header.Set("Sec-Ch-Ua-Mobile", "?1")
	req.Header.Set("Sec-Ch-Ua-Platform", `"Android"`)
	req.Header.Set("Sec-Fetch-Dest", "document")
	req.Header.Set("Sec-Fetch-Mode", "navigate")
	req.Header.Set("Sec-Fetch-Site", "none")
	req.Header.Set("Sec-Fetch-User", "?1")
	req.Header.Set("Upgrade-Insecure-Requests", "1")

	// 创建 HTTP 客户端并设置超时时间
	client := &http.Client{Timeout: 10 * time.Second}

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		log.Printf("发送请求时出错: %v", err)
	}
	defer resp.Body.Close()

	// 检查 HTTP 响应状态码
	if resp.StatusCode != http.StatusOK {
		log.Printf("HTTP 请求失败，状态码: %d", resp.StatusCode)
	}

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Printf("读取响应体时出错: %v", err)
	}

	// 解析 JSON 数据
	var ipInfo IPInfo
	if err := json.Unmarshal(body, &ipInfo); err != nil {
		log.Printf("解析 JSON 时出错: %v", err)
	}

	//fmt.Printf("%s%s\n", ipInfo.Data.Continent, ipInfo.Data.Country)

	return fmt.Sprintf("%s%s\n", ipInfo.Data.Continent, ipInfo.Data.Country), err
}
