import * as anchor from "@coral-xyz/anchor";
import { getMint, Mint } from "@solana/spl-token";
import { Connection, PublicKey } from "@solana/web3.js";
import { ETFNotExistsError } from "./error";

export function deriveEtfTokenMintAccount(program: anchor.Program, seeds: (string | PublicKey)[],): [anchor.web3.PublicKey, number] {
    const buffers = seeds.map(part => {
        if (typeof part === 'string') {
            return Buffer.from(part); // 字符串直接转换为 Buffer
        } else if (part instanceof PublicKey) {
            return part.toBuffer(); // PublicKey 转换为 Buffer
        } else {
            throw new Error(`Unsupported type in symbolParts: ${typeof part}`);
        }
    });


    return anchor.web3.PublicKey.findProgramAddressSync(
        [
            ...buffers
        ],
        program.programId,
    );
}



// export async function checkETFExists(etfAddress: PublicKey, connection: Connection): Promise<void> {
//     try {


//         const mintInfo: Mint = await getMint(connection, etfAddress);
//         console.log('ETF合约已存在:', mintInfo.address.toBase58());
//         return;
//     } catch (error) {
//         if (error instanceof Error && error.message.includes('Account does not exist')) {
//             throw new ETFNotExistsError(`ETF合约不存在: ${etfAddress}`);
//         } else {
//             throw new Error(`检查ETF合约时发生错误: ${error.message}`);
//         }
//     }
// }0x9826eF6A1aFb97Bc7C2473B1D893A1067023bAF8

export function getSavedContractAddresses() {
    let json = {
        "hardhat": {
            "TWAP": "0xDb731EaaFA0FFA7854A24C2379585a85D768Ed5C",
            "CETO": "0x335796f7A0F72368D1588839e38f163d90C92C80",
            "ETFROUTER": "0xa86582Ad5E80abc19F95f8A9Fb3905Cda0dAbd59",
            "ETFFACTORY": "0x97915c43511f8cB4Fbe7Ea03B96EEe940eC4AF12",
        },
        "localhost": {
            "TWAP": "0xDb731EaaFA0FFA7854A24C2379585a85D768Ed5C",
            "CETO": "0x335796f7A0F72368D1588839e38f163d90C92C80",
            "ETFROUTER": "0xa86582Ad5E80abc19F95f8A9Fb3905Cda0dAbd59",
            "ETFFACTORY": "0x97915c43511f8cB4Fbe7Ea03B96EEe940eC4AF12",
            "WETH": "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"
        },
        "arbitrumSepolia": {
            "TWAP": "0x5571Af8f9277E5b00DDF5fdA7738eA01d9fc5dFe",
            "CETO": "0x197D6Fe658Eb2D9fa3eEE5d6F079ce1E1619Ad9b",
            "ETFROUTER": "0xE2B2efFC24c7e3Fe1ABb1c3eDD33481d9a7d9346",
            "ETFFACTORY": "0xD324c3B60B94b9Fe8aaA66F4A44a5b3a3Dbcb811",
            "WETH": "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"
        },
        "sepolia": {
            "TWAP": "0x5617E6B8d33E4bE32c1c8eA140998bf6c1280E2D",
            "CETO": "0xC0Fc8583c7c308ea92471d3897cA04514615C84D",
            "ETFROUTER": "0x84E8120aC983b3125737DAebED2C579e9a9967F1",
            "ETFFACTORY": "0x21cFE67901E071fc178a1D766414Dfa20E285209",
            "WETH": "0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14"
        },
    }

    return json;
}