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

import {Script, console} from "forge-std/Script.sol";
import {CCIPLogger} from "../contracts/ccip-integration/CCIPLogger.sol";

/**
 * @title DeployCCIPLogger
 * @notice Deploy CCIPLogger to any chain (Mainnet, BSC, Polygon, Gnosis, Cronos)
 * @dev Set CCIP_ROUTER, CHAIN138_SELECTOR (or chain-specific), AUTHORIZED_SIGNER in .env
 */
contract DeployCCIPLogger is Script {
    function run() external {
        uint256 deployerPrivateKey = vm.envUint("PRIVATE_KEY");
        address deployer = vm.addr(deployerPrivateKey);

        address router = vm.envOr("CCIP_ROUTER", vm.envOr("CCIP_ETH_ROUTER", address(0)));
        if (router == address(0)) {
            // Chain-specific fallbacks
            if (block.chainid == 25) router = vm.envOr("CCIP_CRONOS_ROUTER", address(0xE26B0A098D861d5C7d9434aD471c0572Ca6EAa67));
            if (block.chainid == 1) router = vm.envOr("CCIP_ETH_ROUTER", address(0x80226fc0Ee2b096224EeAc085Bb9a8cba1146f7D));
        }
        require(router != address(0), "CCIP_ROUTER or CCIP_ETH_ROUTER required");

        address authorizedSigner = vm.envOr("AUTHORIZED_SIGNER", address(0));
        uint64 sourceChainSelector = uint64(vm.envOr("CHAIN138_SELECTOR", uint256(0x8a))); // 138

        console.log("Deploying CCIPLogger...");
        console.log("  Chain ID:", block.chainid);
        console.log("  Router:", router);
        console.log("  Source Chain Selector:", sourceChainSelector);

        vm.startBroadcast(deployerPrivateKey);
        CCIPLogger logger = new CCIPLogger(router, authorizedSigner, sourceChainSelector);
        vm.stopBroadcast();

        console.log("CCIPLogger deployed:", address(logger));
        console.log("Add to .env: CCIP_LOGGER_%s=%s", _chainName(), address(logger));
    }

    function _chainName() internal view returns (string memory) {
        if (block.chainid == 1) return "MAINNET";
        if (block.chainid == 25) return "CRONOS";
        if (block.chainid == 56) return "BSC";
        if (block.chainid == 137) return "POLYGON";
        if (block.chainid == 100) return "GNOSIS";
        if (block.chainid == 138) return "CHAIN138";
        return "ADDRESS";
    }
}
