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

import {Script, console2} from "forge-std/Script.sol";
import {CWTokenMarketRegistry} from "../../contracts/mainnet-market/CWTokenMarketRegistry.sol";
import {CWTokenUsdFeed} from "../../contracts/mainnet-market/CWTokenUsdFeed.sol";
import {IAggregatorV3} from "../../contracts/mainnet-market/interfaces/IAggregatorV3.sol";

/// @notice Register mainnet cWBTC with live Chainlink BTC/USD face (8 decimals).
contract RegisterCWBTMarketToken is Script {
    address internal constant CWBTC = 0x2BBe3c809386FA5349EB2da31E0848ee9f54EE59;
    address internal constant CHAINLINK_BTC_USD = 0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c;

    function run() external {
        address registryAddr = vm.envAddress("CW_MARKET_REGISTRY_MAINNET");
        CWTokenMarketRegistry registry = CWTokenMarketRegistry(registryAddr);

        if (registry.tokenFeed(CWBTC) != address(0)) {
            console2.log("skip already registered cWBTC", CWBTC);
            console2.log("  feed", registry.tokenFeed(CWBTC));
            return;
        }

        (, int256 answer,, uint256 updatedAt,) = IAggregatorV3(CHAINLINK_BTC_USD).latestRoundData();
        require(answer > 0, "chainlink btc/usd stale");
        require(updatedAt > 0, "chainlink btc/usd no timestamp");
        uint64 faceUsdE8 = uint64(uint256(answer));
        require(faceUsdE8 > 0, "zero btc usd");

        console2.log("Chainlink BTC/USD faceUsdE8", faceUsdE8);

        vm.startBroadcast();
        CWTokenUsdFeed feed = new CWTokenUsdFeed(registry, CWBTC, "cWBTC / USD (GRU market anchor)");
        registry.registerToken(CWBTC, 8, faceUsdE8, address(0), true, address(feed));
        vm.stopBroadcast();

        console2.log("Registered cWBTC", CWBTC);
        console2.log("  feed", address(feed));
        console2.log("CWTokenMarketRegistry", registryAddr);
    }
}
