import { ethers, upgrades } from "hardhat";
import * as fs from "fs";
import * as path from "path";

/**
 * 验证 YTAssetVault 升级结果
 * 
 * 功能：
 * 1. 检查 Factory 的实现地址是否已更新
 * 2. 验证现有 Vault 的实现地址
 * 3. 测试新功能是否可用
 */
async function main() {
    console.log("\n==========================================");
    console.log("🔍 验证 YTAssetVault 升级结果");
    console.log("==========================================\n");

    // ========== 读取部署信息 ==========
    const deploymentsPath = path.join(__dirname, "../../deployments-vault-system.json");
    if (!fs.existsSync(deploymentsPath)) {
        throw new Error("未找到部署信息文件");
    }
    
    const deployments = JSON.parse(fs.readFileSync(deploymentsPath, "utf-8"));
    const factory = await ethers.getContractAt(
        "YTAssetFactory",
        deployments.contracts.YTAssetFactory.proxy
    );

    // ========== 验证 Factory ==========
    console.log("📋 验证 Factory 配置");
    console.log("=====================================");
    
    const currentImplInFactory = await factory.vaultImplementation();
    const expectedImpl = deployments.contracts.YTAssetVault.implementation;
    
    console.log("Factory Proxy:           ", deployments.contracts.YTAssetFactory.proxy);
    console.log("当前 vaultImplementation:", currentImplInFactory);
    console.log("配置文件中的实现:       ", expectedImpl);
    
    if (currentImplInFactory.toLowerCase() === expectedImpl.toLowerCase()) {
        console.log("✅ Factory 配置正确！\n");
    } else {
        console.log("❌ Factory 配置不匹配！\n");
    }

    // ========== 验证已部署的 Vaults ==========
    const vaults = deployments.vaults || [];
    
    if (vaults.length === 0) {
        console.log("ℹ️  没有已部署的 Vault\n");
        return;
    }

    console.log("📋 验证已部署的 Vaults");
    console.log("=====================================");
    console.log(`发现 ${vaults.length} 个 Vault\n`);

    const results: any[] = [];

    for (let i = 0; i < vaults.length; i++) {
        const vaultInfo = vaults[i];
        console.log(`[${i + 1}/${vaults.length}] 检查 ${vaultInfo.symbol} (${vaultInfo.address})`);
        
        try {
            // 获取实现地址
            const implAddress = await upgrades.erc1967.getImplementationAddress(vaultInfo.address);
            const isUpgraded = implAddress.toLowerCase() === expectedImpl.toLowerCase();
            
            console.log(`  实现地址: ${implAddress}`);
            console.log(`  状态: ${isUpgraded ? '✅ 已升级' : '⏸️  未升级'}`);
            
            // 如果已升级，测试新功能
            if (isUpgraded) {
                const vault = await ethers.getContractAt("YTAssetVault", vaultInfo.address);
                
                try {
                    // 测试新增的状态变量
                    const pendingCount = await vault.pendingRequestsCount();
                    const requestIdCounter = await vault.requestIdCounter();
                    const processedUpToIndex = await vault.processedUpToIndex();
                    
                    console.log(`  新功能验证:`);
                    console.log(`    - pendingRequestsCount: ${pendingCount}`);
                    console.log(`    - requestIdCounter: ${requestIdCounter}`);
                    console.log(`    - processedUpToIndex: ${processedUpToIndex}`);
                    
                    // 测试新增的查询函数
                    const queueProgress = await vault.getQueueProgress();
                    console.log(`    - 队列进度: ${queueProgress[0]}/${queueProgress[1]} (待处理: ${queueProgress[2]})`);
                    
                    console.log(`  ✅ 新功能工作正常`);
                    
                    results.push({
                        index: i,
                        symbol: vaultInfo.symbol,
                        address: vaultInfo.address,
                        upgraded: true,
                        functional: true
                    });
                } catch (error: any) {
                    console.log(`  ⚠️  新功能测试失败: ${error.message}`);
                    results.push({
                        index: i,
                        symbol: vaultInfo.symbol,
                        address: vaultInfo.address,
                        upgraded: true,
                        functional: false,
                        error: error.message
                    });
                }
            } else {
                results.push({
                    index: i,
                    symbol: vaultInfo.symbol,
                    address: vaultInfo.address,
                    upgraded: false,
                    functional: false
                });
            }
        } catch (error: any) {
            console.log(`  ❌ 检查失败: ${error.message}`);
            results.push({
                index: i,
                symbol: vaultInfo.symbol,
                address: vaultInfo.address,
                upgraded: false,
                functional: false,
                error: error.message
            });
        }
        console.log("");
    }

    // ========== 验证总结 ==========
    console.log("📊 验证总结");
    console.log("=====================================");
    
    const upgraded = results.filter(r => r.upgraded);
    const functional = results.filter(r => r.functional);
    const needsUpgrade = results.filter(r => !r.upgraded);
    
    console.log(`总 Vaults 数量:      ${results.length}`);
    console.log(`已升级:             ${upgraded.length} ✅`);
    console.log(`功能正常:           ${functional.length} ✅`);
    console.log(`待升级:             ${needsUpgrade.length} ${needsUpgrade.length > 0 ? '⏸️' : ''}`);
    console.log("");
    
    if (needsUpgrade.length > 0) {
        console.log("⏸️  待升级的 Vaults:");
        needsUpgrade.forEach(v => {
            console.log(`  [${v.index}] ${v.symbol}: ${v.address}`);
        });
        console.log("");
        console.log("💡 升级命令:");
        console.log(`  factory.upgradeVault("vaultAddress", "${expectedImpl}")`);
        console.log("");
    }

    // ========== 升级历史 ==========
    if (deployments.upgradeHistory && deployments.upgradeHistory.length > 0) {
        console.log("📜 升级历史");
        console.log("=====================================");
        deployments.upgradeHistory.forEach((h: any, idx: number) => {
            console.log(`[${idx + 1}] ${h.timestamp}`);
            console.log(`  升级者: ${h.upgrader}`);
            console.log(`  旧实现: ${h.oldImplementation}`);
            console.log(`  新实现: ${h.newImplementation}`);
        });
        console.log("");
    }

    console.log("✅ 验证完成！\n");
}

main()
    .then(() => process.exit(0))
    .catch((error) => {
        console.error(error);
        process.exit(1);
    });

