const fs = require('fs');
const path = require('path');

// HTML Console endpoint - Simplified and Stable Version
module.exports = {
    rest: {
        method: 'GET',
        fullPath: '/api/workflow/upgrade/approval-comments-console'
    },
    async handler(ctx) {
        const userSession = ctx.meta.user;
        
        // Check if user is admin
        if (!userSession || !userSession.is_space_admin) {
            ctx.meta.$statusCode = 403;
            ctx.meta.$responseType = 'text/html';
            return 'Forbidden: Admin access required';
        }

        // Read documentation files
        const docsPath = path.join(__dirname, '../../');
        const technicalDoc = fs.readFileSync(path.join(docsPath, 'APPROVAL_COMMENTS_UPGRADE.md'), 'utf8');
        const operationsDoc = fs.readFileSync(path.join(docsPath, 'APPROVAL_COMMENTS_OPERATIONS.md'), 'utf8');

        // Detect environment
        const env = process.env.NODE_ENV || 'development';
        const isProduction = env === 'production';

        // HTML page with 3 tabs (simplified, stable version)
        const html = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>审批意见字段升级控制台</title>
    <script src="/unpkg/jquery@3.7.1/dist/jquery.min.js"></script>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background: #f5f5f5;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        header h1 { font-size: 28px; margin-bottom: 8px; }
        header .env-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
            margin-top: 8px;
        }
        header .env-prod { background: #e53e3e; }
        header .env-test { background: #48bb78; }
        
        .tabs {
            display: flex;
            background: #f7fafc;
            border-bottom: 2px solid #e2e8f0;
        }
        .tab {
            flex: 1;
            padding: 16px;
            text-align: center;
            cursor: pointer;
            border: none;
            background: none;
            font-size: 15px;
            font-weight: 500;
            color: #4a5568;
            transition: all 0.2s;
        }
        .tab:hover { background: #edf2f7; }
        .tab.active {
            color: #667eea;
            border-bottom: 3px solid #667eea;
            background: white;
        }
        
        .tab-content {
            padding: 30px;
            display: none;
        }
        .tab-content.active { display: block; }
        
        .doc-content {
            line-height: 1.8;
            color: #2d3748;
            max-height: 600px;
            overflow-y: auto;
            padding: 20px;
            background: #f7fafc;
            border-radius: 6px;
        }
        .doc-content pre {
            background: #1a202c;
            color: #e2e8f0;
            padding: 16px;
            border-radius: 4px;
            overflow-x: auto;
            margin: 16px 0;
        }
        .doc-content code {
            background: #edf2f7;
            padding: 2px 6px;
            border-radius: 3px;
            color: #e53e3e;
            font-size: 90%;
        }
        .doc-content pre code {
            background: none;
            color: inherit;
            padding: 0;
        }
        
        .operation-panel {
            background: #f7fafc;
            padding: 24px;
            border-radius: 6px;
            margin-bottom: 20px;
        }
        .operation-panel h3 {
            color: #2d3748;
            margin-bottom: 16px;
            font-size: 18px;
        }
        .form-group {
            margin-bottom: 16px;
        }
        .form-group label {
            display: block;
            margin-bottom: 6px;
            color: #4a5568;
            font-weight: 500;
        }
        .form-group input[type="text"],
        .form-group input[type="number"] {
            width: 100%;
            padding: 10px;
            border: 1px solid #cbd5e0;
            border-radius: 4px;
            font-size: 14px;
        }
        .form-group input[type="checkbox"] {
            margin-right: 8px;
        }
        
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
            margin-right: 12px;
        }
        .btn-primary {
            background: #667eea;
            color: white;
        }
        .btn-primary:hover { background: #5a67d8; }
        .btn-danger {
            background: #f56565;
            color: white;
        }
        .btn-danger:hover { background: #e53e3e; }
        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .result-panel {
            margin-top: 24px;
            padding: 20px;
            border-radius: 6px;
            display: none;
        }
        .result-panel.success {
            background: #c6f6d5;
            border: 1px solid #9ae6b4;
            color: #22543d;
        }
        .result-panel.error {
            background: #fed7d7;
            border: 1px solid #fc8181;
            color: #742a2a;
        }
        .result-panel h4 {
            margin-bottom: 12px;
            font-size: 16px;
        }
        .result-panel pre {
            background: rgba(0,0,0,0.05);
            padding: 12px;
            border-radius: 4px;
            overflow-x: auto;
            font-size: 13px;
            max-height: 300px;
            overflow-y: auto;
        }
        
        .loading {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 3px solid rgba(255,255,255,.3);
            border-radius: 50%;
            border-top-color: #fff;
            animation: spin 1s ease-in-out infinite;
            margin-left: 8px;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>审批意见字段升级控制台</h1>
            <p>Approval Comments Migration Console</p>
            <span class="env-badge ${isProduction ? 'env-prod' : 'env-test'}">
                环境: ${isProduction ? 'PRODUCTION' : 'TEST/DEV'}
            </span>
        </header>
        
        <div class="tabs">
            <button class="tab" data-tab="tech-doc">📚 技术文档</button>
            <button class="tab" data-tab="ops-manual">📖 操作手册</button>
            <button class="tab active" data-tab="execute">⚙️ 执行操作</button>
        </div>
        
        <div class="tab-content" id="tech-doc">
            <div class="doc-content">
                <pre>${technicalDoc.replace(/</g, '&lt;').replace(/>/g, '&gt;')}</pre>
            </div>
        </div>
        
        <div class="tab-content" id="ops-manual">
            <div class="doc-content">
                <pre>${operationsDoc.replace(/</g, '&lt;').replace(/>/g, '&gt;')}</pre>
            </div>
        </div>
        
        <div class="tab-content active" id="execute">
            <div class="operation-panel">
                <h3>🧪 集成测试 (Integration Test)</h3>
                <p style="color: #666; margin-bottom: 15px;">
                    ${isProduction ? '⚠️ 生产环境禁止运行集成测试' : '✅ 测试环境 - 可以运行自动化测试'}
                </p>
                <button class="btn btn-success" onclick="executeIntegrationTest()" ${isProduction ? 'disabled' : ''}>
                    🧪 运行自动化集成测试
                </button>
                <div class="result-panel" id="test-result"></div>
            </div>
            
            <div class="operation-panel">
                <h3>🚀 升级操作 (Migration)</h3>
                <div class="form-group">
                    <label>
                        <input type="checkbox" id="migrate-dryrun" checked>
                        Dry Run（仅模拟，不实际修改数据）
                    </label>
                </div>
                <div class="form-group">
                    <label>Flow ID (可选，留空则处理所有符合条件的表单):</label>
                    <input type="text" id="migrate-fid" placeholder="示例: 60abc123...">
                </div>
                <div class="form-group">
                    <label>Batch Size (批量大小，默认500):</label>
                    <input type="number" id="migrate-batchsize" value="500" min="1" max="1000">
                </div>
                <button class="btn btn-primary" id="migrate-btn" onclick="executeMigration()">
                    ▶ 执行升级
                </button>
                <div class="result-panel" id="migrate-result"></div>
            </div>
            
            <div class="operation-panel">
                <h3>↩️ 还原操作 (Rollback)</h3>
                <div class="form-group">
                    <label>
                        <input type="checkbox" id="rollback-dryrun" checked>
                        Dry Run（仅模拟，不实际修改数据）
                    </label>
                </div>
                <div class="form-group">
                    <label>Flow ID (可选，留空则处理所有符合条件的表单):</label>
                    <input type="text" id="rollback-fid" placeholder="示例: 60abc123...">
                </div>
                <div class="form-group">
                    <label>Batch Size (批量大小，默认500):</label>
                    <input type="number" id="rollback-batchsize" value="500" min="1" max="1000">
                </div>
                <button class="btn btn-danger" id="rollback-btn" onclick="executeRollback()">
                    ↩️ 执行还原
                </button>
                <div class="result-panel" id="rollback-result"></div>
            </div>
        </div>
    </div>
    
    <script>
        // Tab switching
        $('.tab').click(function() {
            const target = $(this).data('tab');
            $('.tab, .tab-content').removeClass('active');
            $(this).addClass('active');
            $('#' + target).addClass('active');
        });
        
        // Execute migration
        function executeMigration() {
            const dryRun = $('#migrate-dryrun').is(':checked');
            const fid = $('#migrate-fid').val().trim();
            const batchSize = parseInt($('#migrate-batchsize').val()) || 500;
            
            const params = { dryRun, batchSize };
            if (fid) params.fid = fid;
            
            executeOperation('/api/workflow/migrateApprovalCommentsField', params, 'migrate-result');
        }
        
        // Execute rollback
        function executeRollback() {
            if (!confirm('确定要执行还原操作吗？这将恢复字段到旧格式。')) {
                return;
            }
            
            const dryRun = $('#rollback-dryrun').is(':checked');
            const fid = $('#rollback-fid').val().trim();
            const batchSize = parseInt($('#rollback-batchsize').val()) || 500;
            
            const params = { dryRun, batchSize };
            if (fid) params.fid = fid;
            
            executeOperation('/api/workflow/rollbackApprovalCommentsField', params, 'rollback-result');
        }
        
        // Execute integration test
        function executeIntegrationTest() {
            const $btn = $('button[onclick="executeIntegrationTest()"]');
            const $result = $('#test-result');
            
            // Clear previous results and show button loading state
            $btn.prop('disabled', true).text('⏳ 测试中...');
            $result.removeClass('success error').hide();
            
            $.ajax({
                url: '/api/workflow/upgrade/test-approval-comments',
                type: 'GET',
                success: function(data) {
                    // Restore button state
                    $btn.prop('disabled', false).text('🧪 运行自动化集成测试');
                    
                    // Display test results
                    $result.removeClass('error').addClass(data.success ? 'success' : 'error').show();
                    
                    let html = '<h4>' + (data.success ? '✅ 测试通过' : '❌ 测试失败') + '</h4>';
                    html += '<p><strong>总测试数:</strong> ' + data.summary.totalTests + '</p>';
                    html += '<p><strong>通过:</strong> ' + data.summary.passed + ' | <strong>失败:</strong> ' + data.summary.failed + ' | <strong>跳过:</strong> ' + data.summary.skipped + '</p>';
                    html += '<p><strong>执行时间:</strong> ' + data.executionTime + '</p>';
                    html += '<hr><h5>测试详情:</h5>';
                    data.tests.forEach(function(test) {
                        const icon = test.status === 'passed' ? '✅' : test.status === 'failed' ? '❌' : '⏭️';
                        html += '<p>' + icon + ' ' + test.name + ': ' + test.message + '</p>';
                    });
                    if (data.errors.length > 0) {
                        html += '<hr><h5>错误信息:</h5>';
                        data.errors.forEach(function(err) {
                            html += '<p style="color: red;">• ' + err + '</p>';
                        });
                    }
                    html += '<details style="margin-top:15px"><summary>▼ 展开完整结果</summary><pre style="background:#f5f5f5;padding:10px;border-radius:4px">' + JSON.stringify(data, null, 2) + '</pre></details>';
                    $result.html(html);
                },
                error: function(xhr) {
                    // Restore button state
                    $btn.prop('disabled', false).text('🧪 运行自动化集成测试');
                    
                    // Display error result
                    $result.removeClass('success').addClass('error').show();
                    const errorMsg = xhr.responseJSON || xhr.responseText || '未知错误';
                    $result.html('<h4>❌ 测试失败</h4><pre style="background:#f5f5f5;padding:10px;border-radius:4px">' + JSON.stringify(errorMsg, null, 2) + '</pre></details>');
                }
            });
        }
        
        // Execute operation
        function executeOperation(url, params, resultId) {
            const $btn = $('#' + resultId.replace('-result', '-btn'));
            const $result = $('#' + resultId);
            
            // Clear previous results and show button loading state
            $btn.prop('disabled', true).text('⏳ 执行中...');
            $result.removeClass('success error').hide();
            
            $.ajax({
                url: url,
                type: 'GET',
                data: params,
                success: function(data) {
                    // Restore button state
                    $btn.prop('disabled', false).text($btn.attr('id') === 'migrate-btn' ? '▶ 执行升级' : '↩️ 执行还原');
                    
                    // Display success result
                    $result.removeClass('error').addClass('success').show();
                    
                    let html = '<h4>✅ 操作成功</h4>';
                    html += '<hr style="margin: 10px 0;">';
                    html += '<div style="line-height: 2;"><strong>📊 统计信息:</strong></div>';
                    html += '<p>• 处理表单数: <strong>' + (data.totalForms || 0) + '</strong></p>';
                    html += '<p>• 处理字段数: <strong>' + (data.totalFields || 0) + '</strong></p>';
                    html += '<p>• 错误数: <strong style="color:' + (data.errors && data.errors.length > 0 ? 'red' : 'green') + '">' + (data.errors ? data.errors.length : 0) + '</strong></p>';
                    if (data.errors && data.errors.length > 0) {
                        html += '<hr><h5>错误列表:</h5>';
                        data.errors.forEach(function(err) {
                            html += '<p style="color: red; margin-left: 15px;">• ' + (err.error || err) + '</p>';
                        });
                    }
                    html += '<details style="margin-top:15px"><summary>▼ 展开完整结果</summary><pre style="max-height:300px;overflow:auto;background:#f5f5f5;padding:10px;border-radius:4px">' + JSON.stringify(data, null, 2) + '</pre></details>';
                    $result.html(html);
                },
                error: function(xhr) {
                    // Restore button state
                    $btn.prop('disabled', false).text($btn.attr('id') === 'migrate-btn' ? '▶ 执行升级' : '↩️ 执行还原');
                    
                    // Display error result
                    $result.removeClass('success').addClass('error').show();
                    const errorMsg = xhr.responseJSON || xhr.responseText || '未知错误';
                    $result.html('<h4>❌ 操作失败</h4><pre style="background:#f5f5f5;padding:10px;border-radius:4px">' + JSON.stringify(errorMsg, null, 2) + '</pre>');
                }
            });
        }
    </script>
</body>
</html>
        `;

        // Set response type to HTML
        ctx.meta.$responseType = 'text/html';
        return html;
    }
};
