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

import "forge-std/Script.sol";
import "../../contracts/dbis/DBIS_RootRegistry.sol";
import "../../contracts/dbis/DBIS_ParticipantRegistry.sol";
import "../../contracts/dbis/DBIS_SignerRegistry.sol";
import "../../contracts/dbis/DBIS_GRU_MintController.sol";
import "../../contracts/dbis/DBIS_EIP712Helper.sol";
import "../../contracts/dbis/DBIS_SettlementRouter.sol";
import "../../contracts/dbis/StablecoinReferenceRegistry.sol";
import "../../contracts/dbis/DBIS_ConversionRouter.sol";

/**
 * @title DeployDBISRail
 * @notice Deploy all DBIS Rail contracts (Spec v1 + v1.5) and wire RootRegistry.
 * @dev Run on Chain 138. Env: PRIVATE_KEY; optional ADMIN_ADDRESS (default deployer).
 *      After deploy: set GRU token on MintController; grant MINTER_ROLE on c* tokens to MintController; register stablecoins; add venues/quote issuers.
 */
contract DeployDBISRail is Script {
    function run() external {
        uint256 pk = vm.envUint("PRIVATE_KEY");
        address admin = vm.envOr("ADMIN_ADDRESS", vm.addr(pk));

        vm.startBroadcast(pk);

        DBIS_RootRegistry root = new DBIS_RootRegistry(admin, "v1");
        DBIS_ParticipantRegistry participantReg = new DBIS_ParticipantRegistry(admin);
        DBIS_SignerRegistry signerReg = new DBIS_SignerRegistry(admin);
        DBIS_GRU_MintController mintController = new DBIS_GRU_MintController(admin, address(0));
        address eip712LibAddr = address(new DBIS_EIP712Helper());
        DBIS_SettlementRouter router = new DBIS_SettlementRouter(admin, address(root), eip712LibAddr);
        StablecoinReferenceRegistry stableReg = new StablecoinReferenceRegistry(admin);
        DBIS_ConversionRouter conversionRouter = new DBIS_ConversionRouter(admin, address(root), eip712LibAddr);

        root.setComponent(keccak256("ParticipantRegistry"), address(participantReg));
        root.setComponent(keccak256("SignerRegistry"), address(signerReg));
        root.setComponent(keccak256("GRUMintController"), address(mintController));
        mintController.setSettlementRouter(address(router));

        root.setComponent(keccak256("SettlementRouter"), address(router));
        root.setComponent(keccak256("StablecoinReferenceRegistry"), address(stableReg));
        root.setComponent(keccak256("ConversionRouter"), address(conversionRouter));

        signerReg.setSwapQuorum(1e24, 2, 3);

        console.log("DBIS_EIP712Helper", eip712LibAddr);
        console.log("DBIS_RootRegistry", address(root));
        console.log("DBIS_ParticipantRegistry", address(participantReg));
        console.log("DBIS_SignerRegistry", address(signerReg));
        console.log("DBIS_GRU_MintController", address(mintController));
        console.log("DBIS_SettlementRouter", address(router));
        console.log("StablecoinReferenceRegistry", address(stableReg));
        console.log("DBIS_ConversionRouter", address(conversionRouter));

        vm.stopBroadcast();
    }
}
