#!/usr/bin/env node

/**
 * Zustand 迁移自动化测试脚本
 * 测试范围：P0 核心配置 + P1 主要页面
 */

import http from 'http';
import assert from 'assert';

// 配置
const BASE_URL = 'http://localhost:3100';
const TIMEOUT = 10000;

// 颜色输出
const colors = {
    reset: '\x1b[0m',
    green: '\x1b[32m',
    red: '\x1b[31m',
    yellow: '\x1b[33m',
    blue: '\x1b[34m',
};

// 测试工具
const TestUtil = {
    // HTTP GET 请求
    async get(path) {
        return new Promise((resolve, reject) => {
            const url = new URL(path, BASE_URL);
            http.get(url, (res) => {
                let data = '';
                res.on('data', (chunk) => data += chunk);
                res.on('end', () => {
                    resolve({
                        statusCode: res.statusCode,
                        headers: res.headers,
                        body: data,
                    });
                });
            }).on('error', reject);
            
            setTimeout(() => {
                reject(new Error(`Request timeout: ${path}`));
            }, TIMEOUT);
        });
    },

    // 断言页面正常加载
    assertPageLoaded(response, pageName) {
        assert.strictEqual(
            response.statusCode, 
            200, 
            `${pageName} 页面加载失败，状态码：${response.statusCode}`
        );
        assert.ok(
            response.body.length > 0,
            `${pageName} 页面内容为空`
        );
    },

    // 断言无 MobX 错误
    assertNoMobxError(response, pageName) {
        if (response.body.toLowerCase().includes('mobx')) {
            console.warn(`${colors.yellow}警告：${pageName} 页面仍包含 MobX 引用${colors.reset}`);
        }
    },

    // 断言使用 Zustand
    assertUsesZustand(response, pageName) {
        // 检查是否使用了 Zustand store
        if (response.body.includes('useAppStore') || 
            response.body.includes('useLoginStore') ||
            response.body.includes('useLayoutStore') ||
            response.body.includes('useHomeStore') ||
            response.body.includes('useKnowledgeLibListStore') ||
            response.body.includes('useQuestionAnswerInfoStore') ||
            response.body.includes('useChatStore')) {
            console.log(`  ✅ ${pageName} 使用 Zustand`);
        }
    },
};

// 测试用例
const tests = [
    {
        name: 'P0 - 登录页面',
        path: '/login',
        test: async (response) => {
            TestUtil.assertPageLoaded(response, '登录页面');
            TestUtil.assertNoMobxError(response, '登录页面');
            TestUtil.assertUsesZustand(response, '登录页面');
            
            // 检查是否自动跳转（Demo 模式）
            if (response.body.includes('useLoginStore')) {
                console.log('  ✅ 登录页面使用 useLoginStore');
            }
        },
    },
    {
        name: 'P0 - 应用广场',
        path: '/appCenter',
        test: async (response) => {
            TestUtil.assertPageLoaded(response, '应用广场');
            TestUtil.assertNoMobxError(response, '应用广场');
            TestUtil.assertUsesZustand(response, '应用广场');
            
            if (response.body.includes('useAppStore')) {
                console.log('  ✅ 应用广场使用 useAppStore');
            }
        },
    },
    {
        name: 'P0 - 首页/控制台',
        path: '/overview',
        test: async (response) => {
            TestUtil.assertPageLoaded(response, '首页');
            TestUtil.assertNoMobxError(response, '首页');
            TestUtil.assertUsesZustand(response, '首页');
            
            if (response.body.includes('useHomeStore')) {
                console.log('  ✅ 首页使用 useHomeStore');
            }
        },
    },
    {
        name: 'P1 - 我创建的应用',
        path: '/appCenter/questionAnswer',
        test: async (response) => {
            TestUtil.assertPageLoaded(response, '我创建的应用');
            TestUtil.assertNoMobxError(response, '我创建的应用');
            TestUtil.assertUsesZustand(response, '我创建的应用');
        },
    },
    {
        name: 'P1 - 创建应用',
        path: '/appCenter/questionAnswer/create',
        test: async (response) => {
            TestUtil.assertPageLoaded(response, '创建应用');
            TestUtil.assertNoMobxError(response, '创建应用');
            TestUtil.assertUsesZustand(response, '创建应用');
            
            if (response.body.includes('useQuestionAnswerInfoStore')) {
                console.log('  ✅ 创建应用使用 useQuestionAnswerInfoStore');
            }
        },
    },
    {
        name: 'P1 - 知识库列表',
        path: '/knowledge/knowledgeLib',
        test: async (response) => {
            TestUtil.assertPageLoaded(response, '知识库列表');
            TestUtil.assertNoMobxError(response, '知识库列表');
            TestUtil.assertUsesZustand(response, '知识库列表');
            
            if (response.body.includes('useKnowledgeLibListStore')) {
                console.log('  ✅ 知识库列表使用 useKnowledgeLibListStore');
            }
        },
    },
    {
        name: 'P1 - API Key 管理',
        path: '/system/apiKey',
        test: async (response) => {
            TestUtil.assertPageLoaded(response, 'API Key 管理');
            TestUtil.assertNoMobxError(response, 'API Key 管理');
        },
    },
    {
        name: 'P1 - 应用审核',
        path: '/system/audit',
        test: async (response) => {
            TestUtil.assertPageLoaded(response, '应用审核');
            TestUtil.assertNoMobxError(response, '应用审核');
        },
    },
];

// 主函数
async function runTests() {
    console.log(`\n${colors.blue}================================${colors.reset}`);
    console.log(`${colors.blue}Zustand 迁移自动化测试${colors.reset}`);
    console.log(`${colors.blue}================================${colors.reset}\n`);
    
    console.log(`测试目标：${BASE_URL}`);
    console.log(`测试范围：P0 核心配置 + P1 主要页面\n`);
    
    const results = {
        passed: 0,
        failed: 0,
        warnings: 0,
    };
    
    for (const test of tests) {
        try {
            console.log(`运行测试：${test.name}`);
            const response = await TestUtil.get(test.path);
            await test.test(response);
            console.log(`${colors.green}✅ 通过${colors.reset}\n`);
            results.passed++;
        } catch (error) {
            console.log(`${colors.red}❌ 失败：${error.message}${colors.reset}\n`);
            results.failed++;
        }
    }
    
    // 输出总结
    console.log(`\n${colors.blue}================================${colors.reset}`);
    console.log(`${colors.blue}测试总结${colors.reset}`);
    console.log(`${colors.blue}================================${colors.reset}`);
    console.log(`总测试数：${tests.length}`);
    console.log(`${colors.green}通过：${results.passed}${colors.reset}`);
    console.log(`${colors.red}失败：${results.failed}${colors.reset}`);
    console.log(`${colors.yellow}警告：${results.warnings}${colors.reset}`);
    console.log(`成功率：${((results.passed / tests.length) * 100).toFixed(1)}%\n`);
    
    // 退出码
    process.exit(results.failed > 0 ? 1 : 0);
}

// 运行测试
runTests().catch((error) => {
    console.error(`${colors.red}测试执行失败：${error.message}${colors.reset}`);
    process.exit(1);
});
