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

import {Script, console} from "forge-std/Script.sol";
import {Chain138MainnetCheckpoint} from "../../contracts/mainnet-checkpoint/Chain138MainnetCheckpoint.sol";
import {ExtensionIds} from "../../contracts/mainnet-checkpoint/libraries/ExtensionIds.sol";
import {TokenTransferFilterExtension} from "../../contracts/mainnet-checkpoint/extensions/TokenTransferFilterExtension.sol";
import {ICheckpointExtension} from "../../contracts/mainnet-checkpoint/interfaces/ICheckpointExtension.sol";

/// @notice Deploy fixed TokenTransferFilterExtension and swap on hub (revoke + register).
contract ReplaceTokenTransferFilterExtension is Script {
    function run() external {
        uint256 pk = vm.envUint("PRIVATE_KEY");
        address hubAddr = vm.envAddress("CHAIN138_MAINNET_CHECKPOINT_PROXY");
        Chain138MainnetCheckpoint hub = Chain138MainnetCheckpoint(hubAddr);

        vm.startBroadcast(pk);
        TokenTransferFilterExtension filter = new TokenTransferFilterExtension();
        console.log("New TokenTransferFilter:", address(filter));

        bool allowNative = vm.envOr("CHECKPOINT_TOKEN_FILTER_ALLOW_NATIVE", true);
        uint256 minNative = vm.envOr("CHECKPOINT_TOKEN_FILTER_MIN_NATIVE_WEI", uint256(0));
        filter.setAllowNative(allowNative, minNative);

        bytes32 id = ExtensionIds.TOKEN_FILTER;
        (, , bool wasActive) = hub.getExtension(id);
        if (!wasActive) {
            hub.setExtensionActive(id, true);
        }
        hub.revokeExtension(id);
        uint32 hooks = ICheckpointExtension(address(filter)).HOOK_BEFORE_SUBMIT()
            | ICheckpointExtension(address(filter)).HOOK_AFTER_SUBMIT()
            | ICheckpointExtension(address(filter)).HOOK_ON_CCIP()
            | ICheckpointExtension(address(filter)).HOOK_VERIFY_LEAF();
        hub.registerExtension(id, address(filter), hooks);
        hub.setExtensionActive(id, true);
        console.log("TOKEN_FILTER registered and active");
        vm.stopBroadcast();
    }
}
