package main

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

// Response 结构体用于存储整个JSON响应
type JSON struct {
	Code string `json:"code"`
	Data Data   `json:"data"`
	IP   string `json:"ip"`
}

// Data 结构体用于存储"data"字段下的详细信息
type Data struct {
	Continent string `json:"continent"`
	Country   string `json:"country"`
	Zipcode   string `json:"zipcode"`
	Owner     string `json:"owner"`
	Isp       string `json:"isp"`
	Adcode    string `json:"adcode"`
	Prov      string `json:"prov"`
	City      string `json:"city"`
	District  string `json:"district"`
}

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

func SaveBytesToFile(data []byte, filename string, syncToDisk bool) error {
	if filename == "" {
		return fmt.Errorf("filename cannot be empty")
	}

	file, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
	if err != nil {
		return fmt.Errorf("failed to open file %q: %w", filename, err)
	}
	defer file.Close()

	_, err = file.Write(data)
	if err != nil {
		return fmt.Errorf("failed to write to file %q: %w", filename, err)
	}

	if syncToDisk {
		err = file.Sync()
		if err != nil {
			return fmt.Errorf("failed to sync data to disk for file %q: %w", filename, err)
		}
	}

	return nil
}

func main() {
	var (
		err      error
		IP_ADDR  string
		URL_ADDR string

		HTTP_RESP    *http.Response
		HTTP_Request *http.Request
		HTTP_BODY    []byte
		HTTP_CLIENT  *http.Client
		HTPP_JSON    JSON
	)

	if len(os.Args) < 2 {
		log.Fatalf("用法: %s <IP>", os.Args[0])
	}

	IP_ADDR = os.Args[1]
	if !isValidIP(IP_ADDR) {
		log.Fatalf("无效的 IP 地址: %s", IP_ADDR)
	}

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

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

	// 设置请求头
	HTTP_Request.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")
	HTTP_Request.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")
	HTTP_Request.Header.Set("Accept-Encoding", "gzip, deflate, br, zstd")
	HTTP_Request.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
	HTTP_Request.Header.Set("Cache-Control", "max-age=0")
	HTTP_Request.Header.Set("Connection", "keep-alive")
	HTTP_Request.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")
	HTTP_Request.Header.Set("Host", "qifu.baidu.com")
	HTTP_Request.Header.Set("Sec-Ch-Ua", `"Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"`)
	HTTP_Request.Header.Set("Sec-Ch-Ua-Mobile", "?1")
	HTTP_Request.Header.Set("Sec-Ch-Ua-Platform", `"Android"`)
	HTTP_Request.Header.Set("Sec-Fetch-Dest", "document")
	HTTP_Request.Header.Set("Sec-Fetch-Mode", "navigate")
	HTTP_Request.Header.Set("Sec-Fetch-Site", "none")
	HTTP_Request.Header.Set("Sec-Fetch-User", "?1")
	HTTP_Request.Header.Set("Upgrade-Insecure-Requests", "1")

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

	// 发送请求
	HTTP_RESP, err = HTTP_CLIENT.Do(HTTP_Request)
	if err != nil {
		log.Fatalf("发送请求时出错: %v", err)
	}
	defer HTTP_RESP.Body.Close()

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

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

	// 保存响应体到文件（可选）
	if err := SaveBytesToFile(append(HTTP_BODY, '\n'), "response.json", true); err != nil {
		log.Printf("failed to save HTTP response to file: %v", err)
	}

	// 解析 JSON 数据
	err = json.Unmarshal(HTTP_BODY, &HTPP_JSON)
	if err != nil {
		fmt.Println("Error parsing JSON:", err)
		return
	}

	if HTPP_JSON.Code == "Success" {
		fmt.Printf("%s%s\n", HTPP_JSON.Data.Continent, HTPP_JSON.Data.Country)
	} else {
		fmt.Printf("Error!\n")
	}
}
