import requests
import json
import os
import re

def fetch_app_info(pkg):
    """向指定 URL 发送请求并获取内容"""
    base_url = "http://data-api.zhangxinhulian.com/anonymous/getappinfoAndroid"
    params = {"pkg": pkg}

    key_mapping = {
        "packageName": "PACKAGE_NAME",
        "urlEvent": "URL_EVENT",
        "urlApi": "URL_API",
        "urlPrivacy": "URL_PRIVACY",
        "urlUse": "URL_USE",
        "keyAes": "KEY_AES",
        "keySolar": "KEY_SOLAR",
        "keyMax": "KEY_MAX",
        "idAdmobInter": "ID_ADMOB_INTER",
        "idAdmobNative": "ID_ADMOB_NATIVE",
        "idAdmobOpen": "ID_ADMOB_OPEN",
        "idAdmobBanner": "ID_ADMOB_BANNER",
        "idAdmobReward": "ID_ADMOB_REWARD",
        "idMaxInter": "ID_MAX_INTER",
        "idMaxNative": "ID_MAX_NATIVE",
        "idMaxOpen": "ID_MAX_OPEN",
        "idMaxBanner": "ID_MAX_BANNER",
        "idMaxReward": "ID_MAX_REWARD"
    }

    try:
        response = requests.get(base_url, params=params, timeout=10)
        if response.status_code == 200:
            data = response.json()
            if data.get("status") == 200 and data.get("result") and data["result"].get("data"):
                app_data = data["result"]["data"]

                # 设置 packageName 为用户输入的 pkg
                app_data["packageName"] = pkg

                # 将 null 转换为 ""
                app_data = {key: (value if value is not None else "") for key, value in app_data.items()}

                # 打印从服务器获取到的数据字段
                print("从服务器获取到的数据字段值：")
                for key, value in app_data.items():
                    print(f"{key}: {value}")

                # 替换 key
                transformed_data = {key_mapping.get(key, key): value for key, value in app_data.items()}

                # 写入 JSON 文件
                with open("applicationid.json", "w", encoding="utf-8") as file:
                    json.dump(transformed_data, file, ensure_ascii=False, indent=4)
                with open("applicationid.json", "r", encoding="utf-8") as file:
                    json_data = json.load(file)

                # 打印 applicationid.json 文件中的数据
                print("\napplicationid.json 中的数据：")
                print(json_data)
                print("数据已成功以 JSON 格式写入 applicationid.json 文件。")
            else:
                print(f"未找到有效的 data 数据: {data}")
        else:
            print(f"请求失败，状态码: {response.status_code}, 响应内容: {response.text}")
    except requests.RequestException as e:
        print(f"请求发生错误: {e}")

def find_global_config(directory):
    """遍历目录查找 GlobalConfig.kt 文件"""
    for root, dirs, files in os.walk(directory):
        if 'GlobalConfig.kt' in files:
            file_path = os.path.join(root, 'GlobalConfig.kt')
            print(f"找到 GlobalConfig.kt 文件: {file_path}")
            return file_path
    print("未找到 GlobalConfig.kt 文件")
    return None

def update_global_config(file_path, json_data):
    """更新 GlobalConfig.kt 文件中的变量值"""
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()

        # 遍历 JSON 数据中的每个变量名，并在 GlobalConfig.kt 中更新对应的值
        for var_name, var_value in json_data.items():
            # 替换 const val 的值
            pattern_const = rf'\bconst\s+val\s+{re.escape(var_name)}\s*=\s*.*'
            replacement_const = f'const val {var_name} = "{var_value}"'
            content = re.sub(pattern_const, replacement_const, content)

            pattern_inline = rf'\binline\s+val\s+{re.escape(var_name)}\s+get\(\)\s*=\s*.*'
            replacement_inline = f'inline val {var_name} get() = "{var_value}"'

            content = re.sub(pattern_inline, replacement_inline, content)

        # 将修改后的内容写回到 GlobalConfig.kt 文件
        with open(file_path, 'w', encoding='utf-8') as file:
            file.write(content)
        print("\nGlobalConfig.kt 文件已成功更新。")
    except Exception as e:
        print(f"更新文件时发生错误: {e}")


import os
import json

def update_google_services(json_data):
    """更新 google-services.json 文件内容"""
    try:
        # 查找 google-services.json 文件
        google_services_path = os.path.join(os.getcwd(), "google-services.json")
        if os.path.exists(google_services_path):
            print(f"找到 google-services.json 文件: {google_services_path}")

            # 从 applicationid.json 中读取数据
            google_services_raw = json_data.get("googleServices")
            package_name = json_data.get("PACKAGE_NAME")

            if google_services_raw:
                try:
                    # 反序列化 googleServices 的值
                    google_services_data = json.loads(google_services_raw)

                    # 写入反序列化后的数据到 google-services.json
                    with open(google_services_path, "w", encoding="utf-8") as file:
                        json.dump(google_services_data, file, ensure_ascii=False, indent=4)

                    # 读取并打印写入后的内容
                    with open(google_services_path, "r", encoding="utf-8") as file:
                        written_data = file.read()
                        print("\ngoogle-services.json 文件已更新，写入的内容如下：")
                        print(written_data)
                except json.JSONDecodeError as e:
                    print(f"googleServices 值的反序列化失败: {e}")
            else:
                if package_name:
                    print("googleServices 的值为空，尝试更新 package_name。")
                    with open(google_services_path, "r", encoding="utf-8") as file:
                        google_services_data = json.load(file)

                    # 更新 package_name
                    if "client" in google_services_data:
                        for client in google_services_data["client"]:
                            if "client_info" in client and "android_client_info" in client["client_info"]:
                                client["client_info"]["android_client_info"]["package_name"] = package_name
                                print(f"已将 package_name 更新为: {package_name}")

                    # 写入更新后的数据
                    with open(google_services_path, "w", encoding="utf-8") as file:
                        json.dump(google_services_data, file, ensure_ascii=False, indent=4)

                    print("\ngoogle-services.json 文件已更新（更新 package_name）。")
                else:
                    print("未找到 PACKAGE_NAME 值，无法更新 package_name。")
        else:
            print("未找到 google-services.json 文件。")
    except Exception as e:
        print(f"更新 google-services.json 文件时发生错误: {e}")


def update_build_gradle(json_data):
    """更新 build.gradle 或 build.gradle.kts 文件中的 applicationId 值"""
    try:
        # 查找 build.gradle.kts 文件
        build_gradle_kts_path = os.path.join(os.getcwd(), "build.gradle.kts")
        build_gradle_path = os.path.join(os.getcwd(), "build.gradle")
        build_file_path = None
        if os.path.exists(build_gradle_kts_path):
            build_file_path = build_gradle_kts_path
            print(f"找到 build.gradle.kts 文件: {build_file_path}")
        elif os.path.exists(build_gradle_path):
            build_file_path = build_gradle_path
            print(f"找到 build.gradle 文件: {build_file_path}")
        else:
            print("未找到 build.gradle 或 build.gradle.kts 文件。")
            return

        # 从 applicationid.json 中获取 PACKAGE_NAME 的值
        package_name = json_data.get("PACKAGE_NAME")
        if package_name:
            with open(build_file_path, "r", encoding="utf-8") as file:
                content = file.read()

            # 根据文件名选择不同的正则表达式
            if build_file_path.endswith(".kts"):
                # 匹配 applicationId 的值，无论其格式如何（字符串或变量引用）
                pattern = r'applicationId\s*=\s*[^\s]+'
                replacement = f'applicationId = "{package_name}"'
                new_content = re.sub(pattern, replacement, content)
            else:  # build.gradle
                pattern = r'applicationId\s*\'[^\']+\'' #匹配单引号字符串
                replacement = f'applicationId \'{package_name}\''
                new_content = re.sub(pattern, replacement, content)
                if new_content == content: #如果单引号没有匹配到则匹配双引号字符串
                    pattern = r'applicationId\s*"[^"]+"'
                    replacement = f'applicationId "{package_name}"'
                    new_content = re.sub(pattern, replacement, content)
            # 写入更新后的内容
            with open(build_file_path, "w", encoding="utf-8") as file:
                file.write(new_content)

            # 打印更新后的内容
            print(f"\n{os.path.basename(build_file_path)} 文件已更新，更新后的内容如下：")
            print(new_content)
        else:
            print("applicationid.json 中未找到 PACKAGE_NAME 的值。")

    except Exception as e:
        print(f"更新 {os.path.basename(build_file_path)} 文件时发生错误: {e}")


def update_android_manifest(pkg):
    '''更新 AndroidManifest.xml 文件中的 Facebook App ID'''
    try:
        # 查找 AndroidManifest.xml 文件
        file_path = '.\\src\\main\\AndroidManifest.xml'
        if os.path.exists(file_path):
            print(f"找到 AndroidManifest.xml 文件: {file_path}")

            # 从 applicationid.json 中获取 facebookAppId 的值
            facebookAppId = json_data.get("facebookAppId")
            if facebookAppId:
                with open(file_path, "r", encoding="utf-8") as file:
                    content = file.read()

                # 替换 facebookAppId 的值，无论其格式如何（字符串或变量引用）
                pattern = r'<meta-data\s*android:name="com\.facebook\.sdk\.ApplicationId"\s*android:value\s*=\s*[^\s]+'
                replacement = f'<meta-data android:name="com.facebook.sdk.ApplicationId"\n android:value = "{facebookAppId}"'
                new_content = re.sub(pattern, replacement, content)

                # 写入更新后的内容
                with open(file_path, "w", encoding="utf-8") as file:
                    file.write(new_content)

                print("\nAndroidManifest.xml 文件已更新，facebookAppId 更新后的内容如下：")
                print(new_content)
            else:
                print("applicationid.json 中未找到 facebookAppId 的值。")

            # 从 applicationid.json 中获取 adsApplicationId 的值
            adsApplicationId = json_data.get("adsApplicationId")
            if adsApplicationId:
                with open(file_path, "r", encoding="utf-8") as file:
                    content = file.read()

                pattern = r'<meta-data\s*android:name="com\.google\.android\.gms\.ads\.APPLICATION_ID"\s*android:value\s*=\s*[^\s]+'
                replacement = f'<meta-data android:name="com.google.android.gms.ads.APPLICATION_ID"\n android:value = "{adsApplicationId}"'
                new_content = re.sub(pattern, replacement, content)

                # 写入更新后的内容
                with open(file_path, "w", encoding="utf-8") as file:
                    file.write(new_content)

                print("\nAndroidManifest.xml 文件已更新，adsApplicationId 更新后的内容如下：")
                print(new_content)
            else:
                print("applicationid.json 中未找到 adsApplicationId 的值。")

            # 从 applicationid.json 中获取 PACKAGE_NAME 的值
            PACKAGE_NAME = json_data.get("PACKAGE_NAME")
            if PACKAGE_NAME:
                with open(file_path, "r", encoding="utf-8") as file:
                    content = file.read()
                # 更宽松的正则表达式模式
                pattern = r"""
                android:permission="com\.google\.android\.c2dm\.permission\.SEND"\s*>
                \s*<intent-filter>\s*
                \s*<action\s+android:name="com\.google\.firebase\.MESSAGING_EVENT"\s*/>\s*
                \s*<action\s+android:name="com\.google\.android\.c2dm\.intent\.RECEIVE"\s*/>\s*
                \s*<category\s+android:name="([^"]+)"\s*/>\s* # 捕获 category 值
                \s*</intent-filter>
                """
                replacement = f"""
                    android:permission="com.google.android.c2dm.permission.SEND">
                        <intent-filter>
                            <action android:name="com.google.firebase.MESSAGING_EVENT" />
                            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                            <category android:name="{PACKAGE_NAME}" />
                        </intent-filter>
                """

                # 执行替换操作，使用 re.VERBOSE 忽略空白和注释，使用 re.DOTALL 匹配换行
                new_content = re.sub(pattern, replacement, content, flags=re.VERBOSE | re.DOTALL)

                # 判断是否匹配到并进行了替换
                if new_content != content:
                    print("替换成功，内容已更新。")
                    # 将修改后的内容写回文件
                    with open(file_path, 'w', encoding='utf-8') as file:
                        file.write(new_content)
                else:
                    print("没有找到匹配的内容，文件未更改。")

        # pattern = r"""
        #         android:permission="com.google.android.c2dm.permission.SEND">
        #         <intent-filter>(.*?)<category android:name="\s*([^"]+)"
        #         """
        # 
        # replacement = f"""
        #         android:permission="com.google.android.c2dm.permission.SEND">
        #         <intent-filter>\1
        #         <category android:name="{PACKAGE_NAME}"
        #         """
        # 
        # #pattern = r'android:permission="com.google.android.c2dm.permission.SEND">'
        # #r'<intent-filter>'
        # #r'<action android:name="com.google.firebase.MESSAGING_EVENT" />'
        # #r'<action android:name="com.google.android.c2dm.intent.RECEIVE" />'
        # 
        # #r'<category  android:name\s*=\s*[^\s]+' 
        # #replacement = f' android:permission="com.google.android.c2dm.permission.SEND">'
        # #f'<intent-filter>'
        # #f'<action android:name="com.google.firebase.MESSAGING_EVENT" />'
        # #f'<action android:name="com.google.android.c2dm.intent.RECEIVE" /> android:name = "{PACKAGE_NAME}"'
        # new_content = re.sub(pattern, replacement, content)

                # 写入更新后的内容
                with open(file_path, "w", encoding="utf-8") as file:
                    file.write(new_content)

                    print("\nAndroidManifest.xml 文件已更新，c2dm.permission.SEND 更新后的内容如下：")
                    print(new_content)
            else:
                print("applicationid.json 中未找到 PACKAGE_NAME 的值。")

        else:
            print("未找到 AndroidManifest.xml 文件。")
    except Exception as e:
        print(f"更新 AndroidManifest.xml 文件时发生错误: {e}")

if __name__ == "__main__":
    pkg_input = input("请输入 pkg 的值：")
    if pkg_input.strip():
        fetch_app_info(pkg_input.strip())
        
        # 查找 GlobalConfig.kt 文件
        java_src_dir = os.path.join(os.getcwd(), "src", "main", "java")
        global_config_path = find_global_config(java_src_dir)
        
        # 读取 applicationid.json 文件并获取数据
        if global_config_path and os.path.exists("applicationid.json"):
            with open("applicationid.json", "r", encoding="utf-8") as file:
                json_data = json.load(file)

            # 更新 GlobalConfig.kt 文件
            update_global_config(global_config_path, json_data)

            # 更新 google-services.json 文件
            update_google_services(json_data)

            # 更新 build.gradle.kts 文件
            update_build_gradle(json_data)

            # 更新 AndroidManifest.xml
            update_android_manifest(json_data["PACKAGE_NAME"])
            
    else:
        print("pkg 不能为空！")
