import requests
import json
import os
import re


def load_mapping():
    """Load the obfuscation mapping from mapping.json"""
    try:
        with open("mapping.json", "r", encoding="utf-8") as f:
            mapping = json.load(f)
            return mapping.get("class", {})
    except (FileNotFoundError, json.JSONDecodeError) as e:
        print(f"Warning: Could not load mapping.json - {e}")
        return {}


def find_obfuscated_file(directory, original_name, mapping):
    """Find the obfuscated file name in the given directory"""
    obfuscated_name = mapping.get(original_name, original_name)
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file == f"{obfuscated_name}.kt" or file == f"{original_name}.kt":
                file_path = os.path.join(root, file)
                print(f"Found config file: {file_path}")
                return file_path
    print(f"Could not find {obfuscated_name}.kt or {original_name}.kt in {directory}")
    return None


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"]
                app_data["packageName"] = pkg
                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}")

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

                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)

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

        ads_application_id = json_data.get("adsApplicationId")
        if ads_application_id:
            pattern = r'\binline\s+val\s+ID_ADMOB_APPLICATION\s+get\(\)\s*=\s*.*'
            replacement = f'inline val ID_ADMOB_APPLICATION get() = "{ads_application_id}"'
            content = re.sub(pattern, replacement, content)

        facebook_app_id = json_data.get("facebookAppId")
        if facebook_app_id:
            pattern = r'\binline\s+val\s+ID_FACEBOOK\s+get\(\)\s*=\s*.*'
            replacement = f'inline val ID_FACEBOOK get() = "{facebook_app_id}"'
            content = re.sub(pattern, replacement, content)

        for var_name, var_value in json_data.items():
            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)

        with open(file_path, 'w', encoding='utf-8') as file:
            file.write(content)
        print("\n配置文件已成功更新。")
    except Exception as e:
        print(f"更新文件时发生错误: {e}")


def update_google_services(json_data):
    """更新 google-services.json 文件内容"""
    try:
        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}")

            google_services_raw = json_data.get("googleServices")
            package_name = json_data.get("PACKAGE_NAME")

            if google_services_raw:
                try:
                    if google_services_raw.startswith(("https://", "http://")):
                        print(f"检测到 URL，开始下载: {google_services_raw}")
                        response = requests.get(google_services_raw, verify=False)
                        response.raise_for_status()
                        google_services_raw = response.text

                    google_services_data = json.loads(google_services_raw)

                    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 requests.RequestException as e:
                    print(f"下载 googleServices URL 失败: {e}")
                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)

                    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_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

        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"):
                pattern = r'applicationId\s*=\s*[^\s]+'
                replacement = f'applicationId = "{package_name}"'
            else:
                pattern = r'applicationId\s*\'[^\']+\''
                replacement = f'applicationId \'{package_name}\''
                if pattern not in 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:
        file_path = os.path.join('.', 'src', 'main', 'AndroidManifest.xml')
        if os.path.exists(file_path):
            print(f"找到 AndroidManifest.xml 文件: {file_path}")

            facebookAppId = json_data.get("facebookAppId")
            if facebookAppId:
                with open(file_path, "r", encoding="utf-8") as file:
                    content = file.read()

                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 的值。")

            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 的值。")

            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*
                \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>
                """

                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("没有找到匹配的内容，文件未更改。")

                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__":
    # Load obfuscation mapping
    mapping = load_mapping()

    pkg_input = input("请输入 pkg 的值：")
    if pkg_input.strip():
        fetch_app_info(pkg_input.strip())

        # Find the config file (either original or obfuscated name)
        java_src_dir = os.path.join(os.getcwd(), "src", "main", "java")
        config_file_path = find_obfuscated_file(java_src_dir, "GlobalConfig", mapping)

        # Read applicationid.json and update files
        if config_file_path and os.path.exists("applicationid.json"):
            with open("applicationid.json", "r", encoding="utf-8") as file:
                json_data = json.load(file)

            update_global_config(config_file_path, json_data)
            update_google_services(json_data)
            update_build_gradle(json_data)
            update_android_manifest(json_data["PACKAGE_NAME"])

    else:
        print("pkg 不能为空！")