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

import {Script, console2} from "forge-std/Script.sol";
import {Stabilizer} from "../../../contracts/bridge/trustless/integration/Stabilizer.sol";
import {StablecoinPegManager} from "../../../contracts/bridge/trustless/integration/StablecoinPegManager.sol";
import {CommodityPegManager} from "../../../contracts/bridge/trustless/integration/CommodityPegManager.sol";

/// @notice Finish Chain 138 Stabilizer stack after peg managers are already deployed.
/// @dev Env: STABLECOIN_PEG_MANAGER, COMMODITY_PEG_MANAGER, PRIVATE_POOL_REGISTRY, PRIVATE_KEY
contract DeployChain138StabilizerFinish is Script {
    function run() external {
        require(block.chainid == 138, "chain138 only");

        uint256 pk = vm.envUint("PRIVATE_KEY");
        address admin = vm.envOr("STABILIZER_ADMIN", vm.addr(pk));
        address privatePoolRegistry = vm.envAddress("PRIVATE_POOL_REGISTRY");
        address stablecoinPeg = vm.envAddress("STABLECOIN_PEG_MANAGER");
        address commodityPeg = vm.envAddress("COMMODITY_PEG_MANAGER");

        address cUsdc = vm.envOr("COMPLIANT_USDC_ADDRESS", vm.envOr("CUSDC_ADDRESS_138", address(0)));
        address cUsdt = vm.envOr("COMPLIANT_USDT_ADDRESS", vm.envOr("CUSDT_ADDRESS_138", address(0)));
        address weth = vm.envOr("WETH9", address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2));
        address xau = vm.envOr("XAU_ADDRESS_138", vm.envOr("cXAUC_ADDRESS_138", address(0x290E52a8819A4fbD0714E517225429aA2B70EC6b)));

        StablecoinPegManager spm = StablecoinPegManager(stablecoinPeg);
        CommodityPegManager cpm = CommodityPegManager(commodityPeg);

        vm.startBroadcast(pk);

        spm.registerWETH(weth);
        if (xau != address(0)) {
            cpm.setXAUAddress(xau);
            cpm.registerCommodity(xau, "XAU", 1e18);
        }

        Stabilizer stabilizer = new Stabilizer(admin, privatePoolRegistry);
        stabilizer.setStablecoinPegSource(stablecoinPeg, cUsdc != address(0) ? cUsdc : cUsdt);
        if (xau != address(0)) {
            stabilizer.setCommodityPegSource(commodityPeg, xau);
        }

        vm.stopBroadcast();

        console2.log("Stabilizer", address(stabilizer));
        console2.log("StablecoinPegManager", stablecoinPeg);
        console2.log("CommodityPegManager", commodityPeg);
    }
}
