"""Phone application management module.

Provides unified access to application bundle identifiers across different
platforms (ADB for Android, HDC for HarmonyOS, and iOS).
"""

import re
from typing import Literal

from pydantic import BaseModel, Field
from xpdc.adb.device import ADBDevice
from xpdc.hdc.device import HDCDevice

__all__ = ['App', 'apps', 'get']

type DeviceType = Literal['adb', 'hdc', 'ios']
type AppConfig = dict[DeviceType, 'App']


class App(BaseModel):
    """Application configuration.

    Attributes:
        bundle: Application bundle identifier (package name).
        ability: Ability name for HarmonyOS applications (optional).
    """

    bundle: str = Field(..., description='Application bundle identifier')
    ability: str | None = Field(default=None, description='HarmonyOS ability name')


class Apps(dict[tuple[str, ...], AppConfig]):
    """Application registry with fuzzy search support.

    Stores application configurations indexed by multiple name aliases.
    Supports fuzzy matching by normalizing names (removing special characters).
    """

    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        # Cache normalized keys for better performance
        self._normalized_cache: dict[str, AppConfig] = {}
        self._build_cache()

    def _build_cache(self) -> None:
        """Build normalized key cache for O(1) fuzzy lookups."""
        self._normalized_cache.clear()
        for names, app_dict in self.items():
            for name in names:
                normalized = self._normalize_key(name)
                self._normalized_cache[normalized] = app_dict

    @staticmethod
    def _normalize_key(key: str) -> str:
        """Normalize key by removing special characters and converting to lowercase.

        Args:
            key: The key to normalize.

        Returns:
            Normalized key containing only Chinese characters, letters, and digits.
        """
        return re.sub(r'[^\u4e00-\u9fa5a-zA-Z0-9]', '', key.lower())

    def fuzzy_get(self, key: str) -> AppConfig:
        """Get app configuration by fuzzy name matching.

        Args:
            key: App name to search for (case-insensitive, ignores special chars).

        Returns:
            App configuration dictionary for different device types.
            Returns empty dict if no match is found.

        Example:
            >>> apps.fuzzy_get("微信")
            {'adb': App(bundle='com.tencent.mm'), 'hdc': App(bundle='com.tencent.wechat')}
        """
        normalized_key = self._normalize_key(key)
        return self._normalized_cache.get(normalized_key, {})


apps = Apps(
    {
        ('WeChat', '微信'): {
            'adb': App(bundle='com.tencent.mm'),
            'hdc': App(bundle='com.tencent.wechat'),
        },
        ('饿了么',): {'adb': App(bundle='me.ele')},
        ('Google Keep',): {'adb': App(bundle='com.google.android.keep')},
        ('华为应用市场', '应用市场'): {'hdc': App(bundle='com.huawei.hmsapp.appgallery', ability='MainAbility')},
        ('喜马拉雅', 'Himalaya'): {
            'adb': App(bundle='com.ximalaya.ting.android'),
            'hdc': App(bundle='com.ximalaya.ting.xmharmony', ability='MainBundleAbility'),
        },
        ('Google Tasks',): {'adb': App(bundle='com.google.android.apps.tasks')},
        ('美柚',): {'adb': App(bundle='com.lingan.seeyou')},
        ('Chrome', 'Google Chrome'): {'adb': App(bundle='com.android.chrome')},
        ('Duolingo',): {'adb': App(bundle='com.duolingo')},
        ('12306', '铁路12306'): {
            'adb': App(bundle='com.MobileTicket'),
            'hdc': App(bundle='com.chinarailway.ticketingHM'),
        },
        ('拨号', '电话'): {'hdc': App(bundle='com.ohos.callui', ability='com.ohos.callui.ServiceAbility')},
        ('企业微信',): {'hdc': App(bundle='com.tencent.wework.hmos')},
        ('快手',): {
            'adb': App(bundle='com.smile.gifmaker'),
            'hdc': App(bundle='com.kuaishou.hmapp'),
        },
        ('Google Play Books',): {'adb': App(bundle='com.google.android.apps.books')},
        ('海底捞',): {'hdc': App(bundle='com.haidilao.haros')},
        ('华为云盘', '云盘', '云空间'): {'hdc': App(bundle='com.huawei.hmos.clouddrive', ability='MainAbility')},
        ('汽水音乐',): {
            'adb': App(bundle='com.luna.music'),
            'hdc': App(bundle='com.luna.hm.music', ability='MainAbility'),
        },
        ('华为钱包', '钱包'): {'hdc': App(bundle='com.huawei.hmos.wallet', ability='MainAbility')},
        ('Google Clock', 'Clock', '时钟', 'Android Clock', '华为时钟'): {
            'adb': App(bundle='com.google.android.deskclock'),
            'hdc': App(bundle='com.huawei.hmos.clock', ability='com.huawei.hmos.clock.phone'),
        },
        ('华为视频', '视频'): {'hdc': App(bundle='com.huawei.hmsapp.himovie', ability='MainAbility')},
        ('网易云音乐', 'NetEase'): {'adb': App(bundle='com.netease.cloudmusic')},
        ('GoogleFit', 'Google Fit'): {'adb': App(bundle='com.google.android.apps.fitness')},
        ('浏览器', 'Browser'): {'hdc': App(bundle='com.huawei.hmos.browser', ability='MainAbility')},
        ('RetroMusic',): {'adb': App(bundle='code.name.monkey.retromusic')},
        ('Bluecoins',): {'adb': App(bundle='com.rammigsoftware.bluecoins')},
        ('飞书', 'FeiShu'): {
            'adb': App(bundle='com.ss.android.lark'),
            'hdc': App(bundle='com.ss.feishu'),
        },
        ('Twitter', 'X'): {'adb': App(bundle='com.twitter.android')},
        ('去哪儿', '去哪儿旅行'): {'adb': App(bundle='com.Qunar')},
        ('京东', '京东秒送'): {
            'adb': App(bundle='com.jingdong.app.mall'),
            'hdc': App(bundle='com.jd.hm.mall'),
        },
        ('得物',): {'hdc': App(bundle='com.dewu.hos', ability='HomeAbility')},
        ('booking', 'booking.com', 'Booking'): {'adb': App(bundle='com.booking')},
        ('大众点评',): {
            'adb': App(bundle='com.dianping.v1'),
            'hdc': App(bundle='com.sankuai.dianping'),
        },
        ('查找手机', '查找设备'): {'hdc': App(bundle='com.huawei.hmos.finddevice')},
        ('邮件',): {'hdc': App(bundle='com.huawei.hmos.email', ability='ApplicationAbility')},
        ('华为游戏中心', '游戏中心'): {'hdc': App(bundle='com.huawei.hmsapp.gamecenter')},
        ('图库', '相册'): {'hdc': App(bundle='com.huawei.hmos.photos', ability='MainAbility')},
        ('闲鱼',): {'hdc': App(bundle='com.taobao.idlefish4ohos')},
        ('高德地图',): {
            'adb': App(bundle='com.autonavi.minimap'),
            'hdc': App(bundle='com.amap.hmapp'),
        },
        ('腾讯新闻',): {'adb': App(bundle='com.tencent.news')},
        ('Google Contacts', 'Contacts', '联系人', '通讯录'): {
            'adb': App(bundle='com.google.android.contacts'),
            'hdc': App(bundle='com.ohos.contacts', ability='com.ohos.contacts.MainAbility'),
        },
        ('唯品会',): {'hdc': App(bundle='com.vip.hosapp')},
        ('支付宝',): {'hdc': App(bundle='com.alipay.mobile.client')},
        ('拼多多',): {
            'adb': App(bundle='com.xunmeng.pinduoduo'),
            'hdc': App(bundle='com.xunmeng.pinduoduo.hos'),
        },
        ('QQ',): {
            'adb': App(bundle='com.tencent.mobileqq'),
            'hdc': App(bundle='com.tencent.mqq'),
        },
        ('AudioRecorder', 'Audio Recorder', '录音', '录音机'): {
            'adb': App(bundle='com.android.soundrecorder'),
            'hdc': App(bundle='com.huawei.hmos.soundrecorder', ability='MainAbility'),
        },
        ('Joplin',): {'adb': App(bundle='net.cozic.joplin')},
        ('迅雷',): {'hdc': App(bundle='com.xunlei.thunder')},
        ('Google Play Store',): {'adb': App(bundle='com.android.vending')},
        ('优酷视频',): {'adb': App(bundle='com.youku.phone')},
        ('抖音',): {
            'adb': App(bundle='com.ss.android.ugc.aweme'),
            'hdc': App(bundle='com.ss.hm.ugc.aweme', ability='MainAbility'),
        },
        ('淘宝', '淘宝闪购'): {
            'adb': App(bundle='com.taobao.taobao'),
            'hdc': App(bundle='com.taobao.taobao4hmos', ability='Taobao_mainAbility'),
        },
        ('会员中心', '华为会员', '我的华为'): {'hdc': App(bundle='com.huawei.hmos.myhuawei')},
        ('bilibili',): {
            'adb': App(bundle='tv.danmaku.bili'),
            'hdc': App(bundle='yylx.danmaku.bili'),
        },
        ('Osmand',): {'adb': App(bundle='net.osmand')},
        ('Temu',): {'adb': App(bundle='com.einnovation.temu')},
        ('华为阅读', '阅读'): {'hdc': App(bundle='com.huawei.hmsapp.books', ability='MainAbility')},
        (
            'Android System Settings',
            'Settings',
            '系统设置',
            '设置',
        ): {
            'adb': App(bundle='com.android.settings'),
            'hdc': App(bundle='com.huawei.hmos.settings', ability='com.huawei.hmos.settings.MainAbility'),
        },
        ('中国移动',): {'hdc': App(bundle='com.droi.tong')},
        ('File Manager', '文件管理器'): {
            'adb': App(bundle='com.android.fileexplorer'),
            'hdc': App(bundle='com.huawei.hmos.filemanager', ability='MainAbility'),
        },
        ('华为音乐', '音乐'): {'hdc': App(bundle='com.huawei.hmsapp.music', ability='MainAbility')},
        ('Google Drive', 'Drive'): {'adb': App(bundle='com.google.android.apps.docs')},
        ('Reddit',): {'adb': App(bundle='com.reddit.frontpage')},
        ('PiMusicPlayer',): {'adb': App(bundle='com.Project100Pi.themusicplayer')},
        ('Expedia',): {'adb': App(bundle='com.expedia.bookings')},
        ('Google Slides',): {'adb': App(bundle='com.google.android.apps.docs.editors.slides')},
        ('Google Calendar', 'Calendar', '日历'): {
            'adb': App(bundle='com.google.android.calendar'),
            'hdc': App(bundle='com.huawei.hmos.calendar', ability='MainAbility'),
        },
        ('百度', 'Baidu'): {'hdc': App(bundle='com.baidu.baiduapp')},
        ('WPS',): {'hdc': App(bundle='cn.wps.mobileoffice.hap', ability='DocumentAbility')},
        ('FilesbyGoogle', 'GoogleFiles', 'Google Files', 'Files', '文件'): {
            'adb': App(bundle='com.google.android.apps.nbu.files'),
            'hdc': App(bundle='com.huawei.hmos.files'),
        },
        ('信息', '短信'): {'hdc': App(bundle='com.ohos.mms', ability='com.ohos.mms.MainAbility')},
        ('SimpleSMSMessenger',): {'adb': App(bundle='com.simplemobiletools.smsmessenger')},
        ('Google Chat',): {'adb': App(bundle='com.google.android.apps.dynamite')},
        ('崩坏：星穹铁道', '星穹铁道'): {'adb': App(bundle='com.miHoYo.hkrpg')},
        ('恋与深空',): {'adb': App(bundle='com.papegames.lysk.cn')},
        ('贝壳找房',): {'adb': App(bundle='com.lianjia.beike')},
        ('小艺', '智能助手'): {'hdc': App(bundle='com.huawei.hmos.vassistant', ability='AiCaptionServiceExtAbility')},
        ('WhatsApp',): {'adb': App(bundle='com.whatsapp')},
        ('小红书',): {
            'adb': App(bundle='com.xingin.xhs'),
            'hdc': App(bundle='com.xingin.xhs_hos'),
        },
        ('番茄免费小说', '番茄小说'): {'adb': App(bundle='com.dragon.read')},
        ('建设银行',): {'hdc': App(bundle='com.ccb.mobilebank.hm', ability='CcbMainAbility')},
        ('美图秀秀',): {'hdc': App(bundle='com.meitu.meitupic', ability='MainAbility')},
        ('Google Docs',): {'adb': App(bundle='com.google.android.apps.docs.editors.docs')},
        ('国家税务总局',): {'hdc': App(bundle='cn.gov.chinatax.gt4.hm')},
        ('Google Maps',): {'adb': App(bundle='com.google.android.apps.maps')},
        ('指南针',): {'hdc': App(bundle='com.huawei.hmsapp.compass')},
        ('Gmail', 'Google Mail'): {'adb': App(bundle='com.google.android.gm')},
        ('微博',): {
            'adb': App(bundle='com.sina.weibo'),
            'hdc': App(bundle='com.sina.weibo.stage'),
        },
        ('Broccoli',): {'adb': App(bundle='com.flauschcode.broccoli')},
        ('百度地图',): {
            'adb': App(bundle='com.baidu.BaiduMap'),
            'hdc': App(bundle='com.baidu.hmmap'),
        },
        ('爱奇艺',): {
            'adb': App(bundle='com.qiyi.video'),
            'hdc': App(bundle='com.qiyi.video.hmy'),
        },
        ('美团',): {
            'adb': App(bundle='com.sankuai.meituan'),
            'hdc': App(bundle='com.sankuai.hmeituan'),
        },
        ('Telegram',): {'adb': App(bundle='org.telegram.messenger')},
        ('豆瓣',): {'adb': App(bundle='com.douban.frodo')},
        ('备忘录', '笔记'): {'hdc': App(bundle='com.huawei.hmos.notepad', ability='MainAbility')},
        ('VLC',): {'adb': App(bundle='org.videolan.vlc')},
        ('主题', '主题管理'): {'hdc': App(bundle='com.huawei.hmsapp.thememanager', ability='MainAbility')},
        ('同程', '同程旅行'): {'hdc': App(bundle='com.tongcheng.hmos')},
        ('华为地图', '地图'): {'hdc': App(bundle='com.huawei.hmos.maps.app')},
        ('计算器',): {
            'hdc': App(bundle='com.huawei.hmos.calculator', ability='com.huawei.hmos.calculator.CalculatorAbility')
        },
        ('今日头条',): {
            'adb': App(bundle='com.ss.android.article.news'),
            'hdc': App(bundle='com.ss.hm.article.news', ability='MainAbility'),
        },
        ('McDonald',): {'adb': App(bundle='com.mcdonalds.app')},
        ('腾讯视频',): {
            'adb': App(bundle='com.tencent.qqlive'),
            'hdc': App(bundle='com.tencent.videohm', ability='AppAbility'),
        },
        ('58同城',): {'hdc': App(bundle='com.wuba.life')},
        ('安居客',): {'adb': App(bundle='com.anjuke.android.app')},
        ('Tiktok',): {'adb': App(bundle='com.zhiliaoapp.musically')},
        ('录屏',): {
            'hdc': App(
                bundle='com.huawei.hmos.screenrecorder', ability='com.huawei.hmos.screenrecorder.ServiceExtAbility'
            )
        },
        ('美团外卖',): {'hdc': App(bundle='com.meituan.takeaway')},
        ('转转',): {'hdc': App(bundle='com.zhuanzhuan.hmoszz')},
        ('红果短剧',): {'adb': App(bundle='com.phoenix.read')},
        ('同花顺',): {'adb': App(bundle='com.hexin.plat.android')},
        ('芒果TV',): {
            'adb': App(bundle='com.hunantv.imgo.activity'),
            'hdc': App(bundle='com.mgtv.phone'),
        },
        ('中国联通',): {'hdc': App(bundle='com.sinovatech.unicom.ha')},
        ('Quora',): {'adb': App(bundle='com.quora.android')},
        ('扫描全能王',): {'hdc': App(bundle='com.intsig.camscanner.hap')},
        ('快手极速版',): {'hdc': App(bundle='com.kuaishou.hmnebula')},
        ('滴滴出行',): {
            'adb': App(bundle='com.sdu.didi.psnger'),
            'hdc': App(bundle='com.sdu.didi.hmos.psnger'),
        },
        ('相机',): {'hdc': App(bundle='com.huawei.hmos.camera', ability='com.huawei.hmos.camera.MainAbility')},
        ('七猫免费小说',): {'adb': App(bundle='com.kmxs.reader')},
        ('肯德基',): {'adb': App(bundle='com.yek.android.kfc.activitys')},
        ('智慧生活',): {'hdc': App(bundle='com.huawei.hmos.ailife')},
        ('知乎',): {
            'adb': App(bundle='com.zhihu.android'),
            'hdc': App(bundle='com.zhihu.hmos', ability='PhoneAbility'),
        },
        ('华为搜索', '搜索'): {'hdc': App(bundle='com.huawei.hmsapp.hisearch', ability='MainAbility')},
        ('阿里巴巴',): {'hdc': App(bundle='com.alibaba.wireless_hmos')},
        ('健康', '运动健康'): {'hdc': App(bundle='com.huawei.hmos.health', ability='Activity_card_entryAbility')},
        ('华为天气', '天气'): {
            'hdc': App(bundle='com.huawei.hmsapp.totemweather', ability='com.huawei.hmsapp.totemweather.MainAbility')
        },
        ('QQ音乐', 'QQ Music'): {
            'adb': App(bundle='com.tencent.qqmusic'),
            'hdc': App(bundle='com.tencent.hm.qqmusic'),
        },
        ('QQ邮箱',): {'adb': App(bundle='com.tencent.androidqqmail')},
        ('keep', 'Keep'): {'adb': App(bundle='com.gotokeep.keep')},
        ('搜狗输入法',): {'hdc': App(bundle='com.sogou.input')},
        ('SimpleCalendarPro',): {
            'adb': App(bundle='com.scientificcalculatorplus.simplecalculator.basiccalculator.mathcalc')
        },
        ('UC浏览器',): {'hdc': App(bundle='com.uc.mobile')},
        ('携程',): {'adb': App(bundle='ctrip.android.view')},
        ('截屏',): {
            'hdc': App(bundle='com.huawei.hmos.screenshot', ability='com.huawei.hmos.screenshot.ServiceExtAbility')
        },
        ('豆包',): {
            'adb': App(bundle='com.larus.nova'),
            'hdc': App(bundle='com.larus.nova.hm', ability='MainAbility'),
        },
        ('My BMW',): {
            'adb': App(bundle='com.bmw.myBMW.preseries.cn.univ'),
            'hdc': App(bundle='com.bmw.myBMW.preseries.hos.cn.univ'),
        },
    }
)


def get(*, app_name: str, device: ADBDevice | HDCDevice) -> App | None:
    """Get application configuration for specific device.

    Args:
        app_name: Name of the application to retrieve.
        device: Target device (ADB for Android or HDC for HarmonyOS).

    Returns:
        App configuration if found for the device type, None otherwise.

    Example:
        >>> from xpdc.adb.device import ADBDevice
        >>> device = ADBDevice()
        >>> app = get(app_name="微信", device=device)
        >>> print(app.bundle)
        com.tencent.mm
    """
    app_config = apps.fuzzy_get(app_name)
    if isinstance(device, ADBDevice):
        return app_config.get('adb')
    elif isinstance(device, HDCDevice):
        return app_config.get('hdc')
    return None
