import requests
import time
import os
import json

# 环境变量读取
CORPID = os.getenv("CORPID")
CORPSECRET = os.getenv("CORPSECRET")
AGENTID = int(os.getenv("AGENTID"))
CHECK_INTERVAL = int(os.getenv("CRON_INTERVAL", 30)) * 60
CACHE_FILE = "/app/last_ip.cache"

# 获取公网出口IP
def get_public_ip():
    try:
        res = requests.get("https://ifconfig.me", timeout=10)
        return res.text.strip()
    except:
        return requests.get("https://ipinfo.io/ip", timeout=10).text.strip()

# 获取企业微信access_token
def get_token():
    url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={CORPID}&corpsecret={CORPSECRET}"
    resp = requests.get(url).json()
    return resp.get("access_token")

# 更新应用可信IP白名单
def update_trusted_ip(token, new_ip):
    data = {
        "agentid": AGENTID,
        "trusted_ip": new_ip
    }
    resp = requests.post(
        f"https://qyapi.weixin.qq.com/cgi-bin/agent/set?access_token={token}",
        json=data
    ).json()
    print(f"更新结果：{resp}")
    # 推送变更通知到企业微信
    notify_msg(token, f"联通公网IP已变更，自动更新可信IP：{new_ip}")

# 推送通知消息
def notify_msg(token, content):
    send_data = {
        "touser": "@all",
        "agentid": AGENTID,
        "msgtype": "text",
        "text": {"content": content}
    }
    requests.post(
        f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}",
        json=send_data
    )

# 读取缓存上次IP
def get_last_ip():
    if os.path.exists(CACHE_FILE):
        with open(CACHE_FILE, "r", encoding="utf-8") as f:
            return f.read().strip()
    return ""

# 写入新IP缓存
def save_ip(ip):
    with open(CACHE_FILE, "w", encoding="utf-8") as f:
        f.write(ip)

# 主循环
if __name__ == "__main__":
    print("企业微信可信IP自动更新服务启动，每{}分钟检测一次".format(CHECK_INTERVAL//60))
    while True:
        curr_ip = get_public_ip()
        last_ip = get_last_ip()
        if curr_ip != last_ip:
            print(f"IP发生变化：{last_ip} → {curr_ip}，执行更新")
            token = get_token()
            if token:
                update_trusted_ip(token, curr_ip)
                save_ip(curr_ip)
            else:
                print("获取access_token失败，请检查Corpid/Secret")
        else:
            print(f"IP未变更：{curr_ip}，跳过更新")
        time.sleep(CHECK_INTERVAL)