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

import {Vm} from "forge-std/Vm.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {AaveQuotePushFlashReceiver} from "../../../contracts/flash/AaveQuotePushFlashReceiver.sol";

/**
 * @title QuotePushCollateralEnv
 * @notice Build `QuotePushParams.collateral` from optional env vars for mainnet quote-push scripts.
 *
 * Env (all optional — empty when counts are zero / unset):
 *   QUOTE_PUSH_COLLATERAL_SUPPLY_COUNT
 *   QUOTE_PUSH_COLLATERAL_SUPPLY_{i}_ASSET
 *   QUOTE_PUSH_COLLATERAL_SUPPLY_{i}_AMOUNT_RAW
 *
 *   QUOTE_PUSH_COLLATERAL_TOGGLE_BEFORE_COUNT
 *   QUOTE_PUSH_COLLATERAL_TOGGLE_BEFORE_{i}_ASSET
 *   QUOTE_PUSH_COLLATERAL_TOGGLE_BEFORE_{i}_ENABLE   (1 = true, 0 = false)
 *
 *   QUOTE_PUSH_COLLATERAL_TOGGLE_AFTER_COUNT
 *   QUOTE_PUSH_COLLATERAL_TOGGLE_AFTER_{i}_ASSET
 *   QUOTE_PUSH_COLLATERAL_TOGGLE_AFTER_{i}_ENABLE
 *
 *   QUOTE_PUSH_COLLATERAL_TOGGLE_BEFORE_UNWIND_COUNT
 *   QUOTE_PUSH_COLLATERAL_TOGGLE_BEFORE_UNWIND_{i}_ASSET
 *   QUOTE_PUSH_COLLATERAL_TOGGLE_BEFORE_UNWIND_{i}_ENABLE
 */
library QuotePushCollateralEnv {
    Vm private constant VM = Vm(address(uint160(uint256(keccak256("hevm cheat code")))));

    function loadCollateralParams() internal view returns (AaveQuotePushFlashReceiver.CollateralParams memory params) {
        params.supplyBeforeSwap = _loadSupplies();
        params.toggleBeforeSwap = _loadToggles("QUOTE_PUSH_COLLATERAL_TOGGLE_BEFORE");
        params.toggleAfterSwap = _loadToggles("QUOTE_PUSH_COLLATERAL_TOGGLE_AFTER");
        params.toggleBeforeUnwind = _loadToggles("QUOTE_PUSH_COLLATERAL_TOGGLE_BEFORE_UNWIND");
    }

    function _loadSupplies()
        private
        view
        returns (AaveQuotePushFlashReceiver.CollateralSupplyStep[] memory steps)
    {
        uint256 n = VM.envOr("QUOTE_PUSH_COLLATERAL_SUPPLY_COUNT", uint256(0));
        steps = new AaveQuotePushFlashReceiver.CollateralSupplyStep[](n);
        for (uint256 i = 0; i < n; ++i) {
            string memory prefix = string.concat("QUOTE_PUSH_COLLATERAL_SUPPLY_", Strings.toString(i), "_");
            steps[i].asset = VM.envAddress(string.concat(prefix, "ASSET"));
            steps[i].amount = VM.envUint(string.concat(prefix, "AMOUNT_RAW"));
        }
    }

    function _loadToggles(string memory groupPrefix)
        private
        view
        returns (AaveQuotePushFlashReceiver.CollateralToggleStep[] memory steps)
    {
        string memory countKey = string.concat(groupPrefix, "_COUNT");
        uint256 n = VM.envOr(countKey, uint256(0));
        steps = new AaveQuotePushFlashReceiver.CollateralToggleStep[](n);
        for (uint256 i = 0; i < n; ++i) {
            string memory prefix = string.concat(groupPrefix, "_", Strings.toString(i), "_");
            steps[i].asset = VM.envAddress(string.concat(prefix, "ASSET"));
            steps[i].useAsCollateral = VM.envUint(string.concat(prefix, "ENABLE")) != 0;
        }
    }
}
