const { Pool } = require('pg');
const path = require('path');
require('dotenv').config({ path: path.join(__dirname, '../.env') });

const pool = new Pool({
    user: process.env.DB_USER,
    host: process.env.DB_HOST,
    database: process.env.DB_DATABASE || process.env.DB_NAME,
    password: process.env.DB_PASSWORD,
    port: process.env.DB_PORT,
});

async function debug() {
    const client = await pool.connect();
    try {
        console.log('🔍 开始调试统计数据...');

        // 1. 检查状态分布
        console.log('\n📊 1. 成果状态分布:');
        const statusRes = await client.query('SELECT status, COUNT(*) FROM achievements GROUP BY status');
        console.table(statusRes.rows);

        // 2. 检查部门字段样本
        console.log('\n📋 2. 成果部门字段样本 (前5条):');
        const deptRes = await client.query('SELECT id, assigned_departments FROM achievements LIMIT 5');
        console.table(deptRes.rows);

        // 3. 检查部门表
        console.log('\n🏢 3. 部门表数据:');
        const deptsRes = await client.query('SELECT name FROM departments');
        console.table(deptsRes.rows);

        // 4. 运行统计查询 (模拟 statistics.js 中的查询)
        console.log('\n📈 4. 运行统计查询 (status=\'approved\'):');
        const statsQuery = `
            SELECT 
                d.name as department,
                a.type,
                EXTRACT(YEAR FROM a.achievement_date) as year,
                COUNT(*) as count
            FROM departments d
            JOIN achievements a ON d.name = ANY(a.assigned_departments)
            WHERE a.status = 'approved' AND a.achievement_date IS NOT NULL
            GROUP BY d.name, a.type, year
            ORDER BY d.name
        `;
        const statsRes = await client.query(statsQuery);
        console.log(`查询返回 ${statsRes.rows.length} 行数据`);
        if (statsRes.rows.length > 0) {
            console.table(statsRes.rows.slice(0, 10)); // 只显示前10条
        } else {
            console.log('⚠️ 查询结果为空！');
        }

    } catch (e) {
        console.error('❌ 调试出错:', e);
    } finally {
        client.release();
        await pool.end();
    }
}

debug();
