// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.19;

import "../src/Optimizer.sol";
import { UUPSUpgradeable } from "@openzeppelin/proxy/utils/UUPSUpgradeable.sol";
import "forge-std/Script.sol";

/**
 * @title UpgradeOptimizer
 * @notice Upgrades an existing Optimizer UUPS proxy to OptimizerV3 implementation.
 * @dev Usage:
 *   OPTIMIZER_PROXY=0x... forge script script/UpgradeOptimizer.sol \
 *     --rpc-url <RPC_URL> --broadcast
 *
 *   Key injection (checked in order):
 *     1. PRIVATE_KEY env var (hex private key — for CI/CD)
 *     2. .secret file (BIP-39 seed phrase — for local use)
 *
 *   The caller must be the proxy admin (the address that called initialize()).
 */
contract UpgradeOptimizer is Script {
    function run() public {
        address proxyAddress = vm.envAddress("OPTIMIZER_PROXY");
        require(proxyAddress != address(0), "OPTIMIZER_PROXY env var required");

        // PRIVATE_KEY=0 / empty silently falls back to .secret (0 is an invalid secp256k1 key).
        uint256 privateKey = vm.envOr("PRIVATE_KEY", uint256(0));
        if (privateKey == 0) {
            string memory seedPhrase = vm.readFile(".secret");
            privateKey = vm.deriveKey(seedPhrase, 0);
        }
        vm.startBroadcast(privateKey);
        address sender = vm.addr(privateKey);

        console.log("\n=== Optimizer UUPS Upgrade ===");
        console.log("Proxy address:", proxyAddress);
        console.log("Admin (sender):", sender);

        // Deploy new Optimizer implementation
        Optimizer newImpl = new Optimizer();
        console.log("New Optimizer implementation:", address(newImpl));

        // Upgrade proxy to new implementation (no reinitialize needed — storage layout compatible)
        UUPSUpgradeable(proxyAddress).upgradeTo(address(newImpl));
        console.log("Proxy upgraded to Optimizer");

        // Verify upgrade by calling getLiquidityParams through the proxy
        Optimizer upgraded = Optimizer(proxyAddress);
        (uint256 ci, uint256 as_, uint24 aw, uint256 dd) = upgraded.getLiquidityParams();
        console.log("\n=== Post-Upgrade Verification ===");
        console.log("capitalInefficiency:", ci);
        console.log("anchorShare:", as_);
        console.log("anchorWidth:", uint256(aw));
        console.log("discoveryDepth:", dd);

        vm.stopBroadcast();
    }
}
