// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import {Script, console} from "forge-std/Script.sol";
import {Ledger} from "../../../contracts/vault/Ledger.sol";
import {RegulatedEntityRegistry} from "../../../contracts/vault/RegulatedEntityRegistry.sol";
import {XAUOracle} from "../../../contracts/vault/XAUOracle.sol";
import {RateAccrual} from "../../../contracts/vault/RateAccrual.sol";
import {Liquidation} from "../../../contracts/vault/Liquidation.sol";
import {CollateralAdapter} from "../../../contracts/vault/adapters/CollateralAdapter.sol";
import {eMoneyJoin} from "../../../contracts/vault/adapters/eMoneyJoin.sol";
import {Vault} from "../../../contracts/vault/Vault.sol";
import {VaultFactory} from "../../../contracts/vault/VaultFactory.sol";
import {DepositToken} from "../../../contracts/vault/tokens/DepositToken.sol";
import {DebtToken} from "../../../contracts/vault/tokens/DebtToken.sol";
import {Aggregator} from "../../../contracts/oracle/Aggregator.sol";

/**
 * @title DeployVaultSystem
 * @notice Deployment script for the complete Vault System
 * @dev Deploys all vault system components in the correct order
 */
contract DeployVaultSystem is Script {
    // Deployed contracts
    RegulatedEntityRegistry public entityRegistry;
    Aggregator public ethPriceFeed;
    Aggregator public btcPriceFeed;
    XAUOracle public xauOracle;
    RateAccrual public rateAccrual;
    Ledger public ledger;
    Liquidation public liquidation;
    CollateralAdapter public collateralAdapter;
    eMoneyJoin public eMoneyJoinContract;
    VaultFactory public vaultFactory;

    // Configuration
    address public admin;
    address public treasury; // Treasury address for liquidation proceeds
    address public ethAddress = address(0); // Native ETH
    address public btcAddress; // BTC token address (set in constructor or env)

    // Risk parameters (basis points; Ledger requires liquidationRatio <= 10000)
    uint256 public constant DEFAULT_LIQUIDATION_RATIO = 10000; // 100%
    uint256 public constant DEFAULT_CREDIT_MULTIPLIER = 50000; // 5x
    uint256 public constant DEFAULT_DEBT_CEILING = 1000000e18; // 1M tokens

    function run() external {
        uint256 deployerPrivateKey = vm.envUint("PRIVATE_KEY");
        admin = vm.addr(deployerPrivateKey);
        treasury = vm.envOr("TREASURY_ADDRESS", vm.addr(deployerPrivateKey));

        vm.startBroadcast(deployerPrivateKey);

        console.log("=== Deploying Vault System ===");
        console.log("Admin:", admin);
        console.log("Treasury:", treasury);

        // Step 1: Deploy Regulated Entity Registry
        console.log("\n1. Deploying Regulated Entity Registry...");
        entityRegistry = new RegulatedEntityRegistry(admin);
        console.log("RegulatedEntityRegistry:", address(entityRegistry));

        // Step 2: Deploy Price Feeds
        console.log("\n2. Deploying Price Feeds...");
        ethPriceFeed = new Aggregator("ETH/XAU", admin, 3600, 50);
        ethPriceFeed.addTransmitter(admin);
        ethPriceFeed.updateAnswer(0.05e18); // 1 ETH = 0.05 oz XAU (example)
        console.log("ETH Price Feed:", address(ethPriceFeed));

        btcPriceFeed = new Aggregator("BTC/XAU", admin, 3600, 50);
        btcPriceFeed.addTransmitter(admin);
        btcPriceFeed.updateAnswer(0.5e18); // 1 BTC = 0.5 oz XAU (example)
        console.log("BTC Price Feed:", address(btcPriceFeed));

        // Step 3: Deploy XAU Oracle
        console.log("\n3. Deploying XAU Oracle...");
        xauOracle = new XAUOracle(admin);
        xauOracle.addPriceFeed(address(ethPriceFeed), 10000); // 100% weight
        xauOracle.addPriceFeed(address(btcPriceFeed), 10000); // 100% weight
        xauOracle.updatePrice();
        console.log("XAU Oracle:", address(xauOracle));

        // Step 4: Deploy Rate Accrual
        console.log("\n4. Deploying Rate Accrual...");
        rateAccrual = new RateAccrual(admin);
        rateAccrual.setInterestRate(address(0), 500); // 5% annual
        console.log("Rate Accrual:", address(rateAccrual));

        // Step 5: Deploy Ledger
        console.log("\n5. Deploying Ledger...");
        ledger = new Ledger(admin, address(xauOracle), address(rateAccrual));
        console.log("Ledger:", address(ledger));

        // Step 6: Deploy Liquidation Module
        console.log("\n6. Deploying Liquidation Module...");
        liquidation = new Liquidation(admin, address(ledger), address(xauOracle), treasury);
        console.log("Liquidation:", address(liquidation));

        // Step 7: Deploy Collateral Adapter (constructor: admin, ledger)
        console.log("\n7. Deploying Collateral Adapter...");
        collateralAdapter = new CollateralAdapter(admin, address(ledger));
        console.log("Collateral Adapter:", address(collateralAdapter));

        // Step 8: Deploy eMoney Join Adapter (constructor: admin only)
        console.log("\n8. Deploying eMoney Join Adapter...");
        eMoneyJoinContract = new eMoneyJoin(admin);
        console.log("eMoney Join:", address(eMoneyJoinContract));

        // Step 9: Deploy Vault Factory (constructor: admin, vaultImpl, depositTokenImpl, debtTokenImpl, ledger, entityRegistry, collateralAdapter, eMoneyJoin)
        console.log("\n9. Deploying Vault Factory...");
        Vault vaultImpl = new Vault(admin, admin, address(ledger), address(entityRegistry), address(collateralAdapter), address(eMoneyJoinContract));
        DepositToken depositTokenImpl = new DepositToken();
        DebtToken debtTokenImpl = new DebtToken();
        vaultFactory = new VaultFactory(
            admin,
            address(vaultImpl),
            address(depositTokenImpl),
            address(debtTokenImpl),
            address(ledger),
            address(entityRegistry),
            address(collateralAdapter),
            address(eMoneyJoinContract)
        );
        console.log("Vault Factory:", address(vaultFactory));

        // Step 10: Grant roles and configure
        console.log("\n10. Configuring roles and parameters...");

        // Grant factory vault role
        ledger.grantVaultRole(address(vaultFactory));

        // Set risk parameters (registers assets and sets params)
        ledger.setRiskParameters(
            ethAddress,
            DEFAULT_DEBT_CEILING,
            DEFAULT_LIQUIDATION_RATIO,
            DEFAULT_CREDIT_MULTIPLIER
        );
        if (btcAddress != address(0)) {
            ledger.setRiskParameters(
                btcAddress,
                DEFAULT_DEBT_CEILING,
                DEFAULT_LIQUIDATION_RATIO,
                DEFAULT_CREDIT_MULTIPLIER
            );
        }

        // Grant factory role to create vaults
        entityRegistry.grantRole(keccak256("ENTITY_REGISTRAR_ROLE"), address(vaultFactory));

        vm.stopBroadcast();

        console.log("\n=== Vault System Deployment Complete ===");
        console.log("Summary:");
        console.log("  RegulatedEntityRegistry:", address(entityRegistry));
        console.log("  XAU Oracle:", address(xauOracle));
        console.log("  Rate Accrual:", address(rateAccrual));
        console.log("  Ledger:", address(ledger));
        console.log("  Liquidation:", address(liquidation));
        console.log("  Collateral Adapter:", address(collateralAdapter));
        console.log("  eMoney Join:", address(eMoneyJoinContract));
        console.log("  Vault Factory:", address(vaultFactory));
    }
}
