import { pluginManager } from './pluginManager';
import type { PluginModule } from '../types/plugin';

/**
 * 初始化插件系统
 *  1) 先注册本地演示插件（离线可用，兜底搜索/播放）
 *  2) 从 localStorage 恢复用户插件
 *  3) 从 /plugins/ 目录动态加载官方音源插件（只要部署时有放置）
 *  返回加载结果，可用于在 UI 层显示提示
 */
export interface InitPluginsResult {
    total: number;
    builtins: number;
    user: number;
    fromNet: number;
    activePluginId: string;
    failedBuiltins: string[];
}

const demoPluginModule: PluginModule = {
    pluginInfo: {
        info: {
            id: 'demo',
            name: '演示音源',
            description: '本地演示插件（不依赖网络）',
            version: '1.0.0',
        },
        quality: [
            { id: 'standard', name: '标准', ui: '标' },
        ],
    },
    musicSearch: {
        search: async (query: string, page: number, limit: number) => {
            const baseList = [
                { songmid: 'demo-1', name: '晴天 (Demo)', singer: '周杰伦', albumName: '叶惠美', interval: 269000, img: '', source: 'demo' },
                { songmid: 'demo-2', name: '稻香 (Demo)', singer: '周杰伦', albumName: '魔杰座', interval: 223000, img: '', source: 'demo' },
                { songmid: 'demo-3', name: '七里香 (Demo)', singer: '周杰伦', albumName: '七里香', interval: 299000, img: '', source: 'demo' },
                { songmid: 'demo-4', name: '告白气球 (Demo)', singer: '周杰伦', albumName: '周杰伦的床边故事', interval: 215000, img: '', source: 'demo' },
                { songmid: 'demo-5', name: '夜曲 (Demo)', singer: '周杰伦', albumName: '十一月的萧邦', interval: 237000, img: '', source: 'demo' },
                { songmid: 'demo-6', name: '平凡之路 (Demo)', singer: '朴树', albumName: '猎户星座', interval: 286000, img: '', source: 'demo' },
            ];
            const q = (query || '').toLowerCase().trim();
            const filtered = q ? baseList.filter(s => s.name.toLowerCase().includes(q) || s.singer.toLowerCase().includes(q)) : baseList;
            const start = Math.max(0, (page - 1) * limit);
            return {
                list: filtered.slice(start, start + limit),
                total: filtered.length,
                songCount: filtered.length,
                source: 'demo',
            };
        },
    },
    getUrl: async (_songId: string, _quality: string) => {
        // 演示音源使用公共测试 MP3，仅用于界面演示
        return 'https://www.w3schools.com/html/horse.mp3';
    },
    getLyric: async (_songId: string) => {
        return '[00:00.00]暂无歌词数据\n[00:03.00]演示音源提供占位歌词\n[00:06.00]请切换到官方音源获取真实歌词\n';
    },
};

export const initPlugins = async (): Promise<InitPluginsResult> => {
    let builtins = 0;
    let user = 0;
    let fromNet = 0;
    let failedBuiltins: string[] = [];

    // 1) 注册本地演示插件（始终可用，作为兜底）
    pluginManager.registerModule(demoPluginModule, 'built-in', 'demo');
    builtins++;

    // 2) 恢复用户插件
    user = pluginManager.loadUserPlugins();

    // 3) 浏览器环境下尝试从 /plugins/ 目录加载官方音源
    if (typeof window !== 'undefined' && typeof fetch === 'function') {
        const res = await pluginManager.loadAllBuiltins();
        fromNet = res.loaded;
        builtins += res.loaded;
        failedBuiltins = res.failed;
    }

    // 4) 确保默认激活插件：优先 wy / 首个内置，再是用户的，最后落到 demo
    const active = pluginManager.getActivePluginId();
    const priority = ['wy', 'tx', 'kw', 'kg', 'mg', 'demo'];
    if (!active) {
        for (const id of priority) {
            if (pluginManager.has(id)) {
                pluginManager.setActivePlugin(id);
                break;
            }
        }
    }

    return {
        total: builtins + user,
        builtins,
        user,
        fromNet,
        activePluginId: pluginManager.getActivePluginId(),
        failedBuiltins,
    };
};
