/**
 * 群聊本地总结插件
 * 在群聊工具栏添加「本地总结」按钮，获取最近50条消息生成本地摘要
 * 零上传、零AI依赖
 */
const fs = require('fs');
const path = require('path');

module.exports = {
    name: '群聊本地总结',
    description: '群聊消息本地总结，零上传，生成HTML报告',
    version: '1.0.0-local',

    async init(config, pluginManager) {
        console.log('[GroupLocalSummary] 初始化群聊本地总结插件...');
        this._pm = pluginManager;
        this._instance = { widget: null, toolbarBtn: null, currentTargetId: null };
        this._injectStyles();
        this._observeConversation();
        return this._instance;
    },

    _injectStyles() {
        if (document.querySelector('#group-local-summary-styles')) return;
        try {
            const cssPath = path.join(__dirname, 'styles.css');
            if (fs.existsSync(cssPath)) {
                const style = document.createElement('style');
                style.id = 'group-local-summary-styles';
                style.textContent = fs.readFileSync(cssPath, 'utf-8');
                document.head.appendChild(style);
            }
        } catch (e) { console.error('[GroupLocalSummary] 样式加载失败:', e); }
    },

    _observeConversation() {
        const self = this;
        const check = () => self._syncButton();
        window.addEventListener('hashchange', check);
        const obs = new MutationObserver(check);
        const startObs = () => {
            const app = document.querySelector('#app') || document.body;
            obs.observe(app, { childList: true, subtree: true });
            check();
        };
        setTimeout(startObs, 3000);
    },

    _parseRoute() {
        const hash = window.location.hash || '';
        const match = hash.match(/conversation\/(\d+)\/([^/?]+)/);
        if (!match) return null;
        return { conversationType: parseInt(match[1], 10), targetId: match[2] };
    },

    _syncButton() {
        const route = this._parseRoute();
        const toolbar = document.querySelector('.rong-tools');
        if (!toolbar) return;
        const existing = toolbar.querySelector('#local-summary-btn');
        if (!route || route.conversationType !== 3) {
            if (existing) existing.remove();
            this._instance.currentTargetId = null;
            return;
        }
        this._instance.currentTargetId = route.targetId;
        if (existing) return;

        const btn = document.createElement('button');
        btn.id = 'local-summary-btn';
        btn.title = '本地总结';
        btn.style.cssText = 'width:28px;height:28px;border:none;background:transparent;cursor:pointer;background-size:22px 22px;background-repeat:no-repeat;background-position:center;border-radius:4px;transition:transform 0.15s;padding:0;';

        const makeSvg = (color) => `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="${color}"><path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"/></svg>`;
        const defaultColor = (window.PluginTheme && window.PluginTheme.getNavIconColor()) || '#808CA4';
        const hoverColor = (window.PluginTheme && window.PluginTheme.getNavIconHoverColor()) || '#3A6EE7';
        btn.style.backgroundImage = `url("data:image/svg+xml;base64,${btoa(makeSvg(defaultColor))}")`;
        btn.addEventListener('mouseenter', function() { this.style.backgroundImage = `url("data:image/svg+xml;base64,${btoa(makeSvg(hoverColor))}")`; this.style.transform = 'scale(1.15)'; });
        btn.addEventListener('mouseleave', function() { this.style.backgroundImage = `url("data:image/svg+xml;base64,${btoa(makeSvg(defaultColor))}")`; this.style.transform = 'scale(1)'; });
        btn.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            try { this._generateSummary(); } catch(e) { console.error('[GroupLocalSummary] error:', e); }
        });
        toolbar.insertBefore(btn, toolbar.firstChild);
        this._instance.toolbarBtn = btn;
    },

    async _generateSummary() {
        const targetId = this._instance.currentTargetId;
        if (!targetId) return;

        const RongIMLib = window.RongIMLib;
        if (!RongIMLib || !RongIMLib.RongIMClient) {
            alert('融云 SDK 未就绪');
            return;
        }

        try {
            const RongIMClient = RongIMLib.RongIMClient;
            const result = await new Promise((resolve, reject) => {
                RongIMClient.getInstance().getHistoryMessages(
                    3, targetId, 0, 50,
                    { onSuccess: (list) => resolve(list), onError: (err) => reject(err) }
                );
            });

            if (!result || result.length === 0) {
                alert('没有获取到消息');
                return;
            }

            // 解析用户ID为真实姓名
            const userIds = [...new Set(result.map(m => m.senderUserId).filter(Boolean))];
            const userMap = await this._resolveUsers(userIds);
            for (const msg of result) {
                const info = userMap[msg.senderUserId];
                if (info) msg.senderUserName = info.name || info.alias || msg.senderUserName;
            }

            const report = this._buildReport(result, targetId);
            this._saveReport(report, targetId);
        } catch (e) {
            console.error('[GroupLocalSummary] 获取消息失败:', e);
            alert('获取消息失败: ' + e.message);
        }
    },

    _buildReport(messages, targetId) {
        const participants = new Set();
        const senderCounts = {};
        const timeSlots = {};
        let textContent = '';

        messages.forEach(msg => {
            const sender = msg.senderUserName || msg.senderUserId || '未知';
            participants.add(sender);
            senderCounts[sender] = (senderCounts[sender] || 0) + 1;

            const time = new Date(msg.sentTime);
            const hour = time.getHours();
            const slot = `${Math.floor(hour / 2) * 2}-${Math.floor(hour / 2) * 2 + 2}时`;
            timeSlots[slot] = (timeSlots[slot] || 0) + 1;

            if (msg.content) {
                const msgType = msg.objectName || '';
                let text = '';
                if (msgType === 'RC:TxtMsg' || msgType === 'RC:ReferenceMessage') {
                    text = msg.content.content || '';
                } else if (msgType === 'RC:ImgMsg') {
                    text = '[图片]';
                } else if (msgType === 'RC:FileMsg') {
                    text = '[文件] ' + (msg.content.name || '');
                } else if (msgType === 'RC:VcMsg' || msgType === 'RC:HQVCMsg') {
                    text = '[语音消息]';
                } else if (msgType === 'RC:SightMsg') {
                    text = '[短视频]';
                } else if (msg.content.content && msg.content.content.length < 500 && !msg.content.content.startsWith('data:') && !msg.content.content.startsWith('/9j/')) {
                    text = msg.content.content;
                }
                if (text) {
                    textContent += `[${sender} ${time.toLocaleString('zh-CN')}]: ${text}\n`;
                }
            }
        });

        const topSenders = Object.entries(senderCounts)
            .sort((a, b) => b[1] - a[1])
            .slice(0, 10)
            .map(([name, count], i) => {
                const pct = Math.round(count / messages.length * 100);
                const medal = i === 0 ? '🥇' : i === 1 ? '🥈' : i === 2 ? '🥉' : `${i + 1}.`;
                return `<div style="display:flex;align-items:center;padding:8px 12px;margin:4px 0;background:${i < 3 ? '#f8f9ff' : '#fafafa'};border-radius:8px;">
                    <span style="width:28px;font-size:14px;">${medal}</span>
                    <span style="flex:1;font-weight:500;color:#1d1d1f;">${name}</span>
                    <span style="color:#86868b;font-size:13px;">${count} 条</span>
                    <div style="width:80px;height:6px;background:#e5e5e7;border-radius:3px;margin-left:10px;overflow:hidden;">
                        <div style="width:${pct}%;height:100%;background:linear-gradient(90deg,#3478F6,#2563EB);border-radius:3px;"></div>
                    </div>
                </div>`;
            }).join('');

        const topSlots = Object.entries(timeSlots)
            .sort((a, b) => b[1] - a[1])
            .slice(0, 5)
            .map(([slot, count]) => {
                const pct = Math.round(count / messages.length * 100);
                return `<div style="display:flex;align-items:center;padding:6px 12px;margin:3px 0;background:#fafafa;border-radius:8px;">
                    <span style="flex:1;font-weight:500;color:#1d1d1f;">🕐 ${slot}</span>
                    <span style="color:#86868b;font-size:13px;">${count} 条</span>
                    <div style="width:60px;height:6px;background:#e5e5e7;border-radius:3px;margin-left:10px;overflow:hidden;">
                        <div style="width:${pct}%;height:100%;background:linear-gradient(90deg,#FF9500,#FF6B00);border-radius:3px;"></div>
                    </div>
                </div>`;
            }).join('');

        return `<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>群聊本地总结</title>
<style>
*{margin:0;padding:0;box-sizing:border-box;}
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','PingFang SC','Hiragino Sans GB',sans-serif;max-width:800px;margin:0 auto;padding:32px 24px;background:#f8f8fa;color:#1d1d1f;}
.header{margin-bottom:28px;padding-bottom:20px;border-bottom:1px solid #e5e5e7;}
.header h1{font-size:24px;font-weight:700;display:flex;align-items:center;gap:10px;}
.header .stat{color:#86868b;font-size:13px;margin-top:8px;display:flex;gap:16px;}
.header .stat span{display:flex;align-items:center;gap:4px;}
.section{margin:24px 0;background:#fff;border-radius:14px;padding:20px;box-shadow:0 1px 4px rgba(0,0,0,0.06);}
.section h2{font-size:16px;font-weight:600;margin-bottom:14px;color:#1d1d1f;display:flex;align-items:center;gap:6px;}
pre{background:#f8f8fa;padding:16px;border-radius:10px;overflow-x:auto;white-space:pre-wrap;font-size:13px;line-height:1.7;font-family:'SF Mono','Menlo','Consolas',monospace;border:1px solid #e5e5e7;}
.footer{margin-top:24px;text-align:center;color:#86868b;font-size:12px;}
</style></head>
<body>
<div class="header">
    <h1>📋 群聊本地总结</h1>
    <div class="stat">
        <span>📅 ${new Date().toLocaleString('zh-CN')}</span>
        <span>💬 ${messages.length} 条消息</span>
        <span>👥 ${participants.size} 位参与者</span>
    </div>
</div>
<div class="section"><h2>👥 参与者排行</h2>${topSenders}</div>
<div class="section"><h2>⏰ 活跃时段</h2>${topSlots}</div>
<div class="section"><h2>💬 消息记录</h2><pre>${textContent || '（无文本消息）'}</pre></div>
<div class="footer">由 EpointMsgPlugins 本地生成 · 零上传</div>
</body></html>`;
    },

    /**
     * 批量解析用户ID为姓名
     */
    _resolveUsers(userIds) {
        return new Promise((resolve) => {
            const RongIM = window.RongIM;
            if (!RongIM || !RongIM.dataModel || !RongIM.dataModel.User) {
                resolve({});
                return;
            }
            const map = {};
            let done = 0;
            const total = userIds.length;
            if (total === 0) { resolve(map); return; }
            const timeout = setTimeout(() => resolve(map), 15000);
            userIds.forEach(uid => {
                try {
                    RongIM.dataModel.User.get(uid, (err, user) => {
                        done++;
                        if (!err && user) map[uid] = { name: user.name || '', alias: user.alias || '' };
                        if (done >= total) { clearTimeout(timeout); resolve(map); }
                    });
                } catch (e) {
                    done++;
                    if (done >= total) { clearTimeout(timeout); resolve(map); }
                }
            });
        });
    },

    _saveReport(html, targetId) {
        const reportDir = path.join(process.env.APPDATA || '', 'EpointMsgPluginsLocal', 'reports');
        if (!fs.existsSync(reportDir)) fs.mkdirSync(reportDir, { recursive: true });
        const filename = `群聊总结_${targetId}_${new Date().toISOString().replace(/[:.]/g, '-')}.html`;
        const filepath = path.join(reportDir, filename);
        fs.writeFileSync(filepath, html, 'utf-8');

        try {
            const { shell } = require('electron');
            shell.openPath(filepath);
        } catch (e) {
            console.log('[GroupLocalSummary] 报告已保存:', filepath);
        }
    },

    destroy() {
        const btn = document.querySelector('#local-summary-btn');
        if (btn) btn.remove();
        console.log('[GroupLocalSummary] 已销毁');
    }
};
