const env = import.meta.env;

const LOCAL_PONDER_PATH = '/api/graphql';
const LOCAL_TXNBOT_PATH = '/api/txn';
const LOCAL_RPC_PATH = '/api/rpc';

interface DeploymentContracts {
  Kraiken?: string;
  Stake?: string;
  LiquidityManager?: string;
}

interface DeploymentInfrastructure {
  weth?: string;
}

interface DeploymentsLocal {
  contracts?: DeploymentContracts;
  infrastructure?: DeploymentInfrastructure;
}

// deployments-local.json is gitignored (generated per-run by bootstrap scripts).
// Use a glob pattern (brace expansion) so Vite treats it as dynamic — returns {}
// when the file is absent (CI, production) instead of a hard import error.
const _localFiles = import.meta.glob<DeploymentsLocal>('../../onchain/deployments-local{.json}', {
  eager: true,
  import: 'default',
});
const deploymentsLocal: DeploymentsLocal = _localFiles['../../onchain/deployments-local.json'] ?? {};

const localContracts = deploymentsLocal.contracts ?? {};
const localInfra = deploymentsLocal.infrastructure ?? {};
const LOCAL_KRAIKEN = (env.VITE_KRAIKEN_ADDRESS ?? localContracts.Kraiken ?? '').trim();
const LOCAL_STAKE = (env.VITE_STAKE_ADDRESS ?? localContracts.Stake ?? '').trim();
const LOCAL_LM = (env.VITE_LIQUIDITY_MANAGER ?? localContracts.LiquidityManager ?? '').trim();
const LOCAL_WETH = (env.VITE_LOCAL_WETH ?? localInfra.weth ?? '0x4200000000000000000000000000000000000006').trim();
const LOCAL_ROUTER = (env.VITE_SWAP_ROUTER ?? '0x94cC0AaC535CCDB3C01d6787D6413C739ae12bc4').trim();

function detectDefaultChainId(): number {
  const envValue = import.meta.env.VITE_DEFAULT_CHAIN_ID;
  if (envValue) {
    const parsed = Number(envValue);
    if (Number.isFinite(parsed)) {
      return parsed;
    }
  }

  if (typeof window !== 'undefined') {
    const host = window.location.hostname.toLowerCase();
    if (host === 'localhost' || host === '127.0.0.1' || host === '::1') {
      return 31337;
    }
  }

  return 84532;
}

export const DEFAULT_CHAIN_ID = detectDefaultChainId();

function resolveLocalEndpoint(value: string | undefined, fallback: string): string {
  const candidate = (value ?? fallback).trim();
  if (!candidate) {
    return fallback;
  }

  if (candidate.startsWith('http://') || candidate.startsWith('https://')) {
    return candidate;
  }

  return candidate.startsWith('/') ? candidate : `/${candidate}`;
}

const LOCAL_GRAPHQL_ENDPOINT = resolveLocalEndpoint(env.VITE_PONDER_BASE_SEPOLIA_LOCAL_FORK, LOCAL_PONDER_PATH);
const LOCAL_TXNBOT_ENDPOINT = resolveLocalEndpoint(env.VITE_TXNBOT_BASE_SEPOLIA_LOCAL_FORK, LOCAL_TXNBOT_PATH);
const LOCAL_RPC_ENDPOINT = resolveLocalEndpoint(env.VITE_LOCAL_RPC_URL, LOCAL_RPC_PATH);

export const chainsData = [
  {
    // local base sepolia fork
    id: 31337,
    graphql: LOCAL_GRAPHQL_ENDPOINT,
    path: 'local',
    stake: LOCAL_STAKE,
    harb: LOCAL_KRAIKEN,
    uniswap: '',
    cheats: {
      weth: LOCAL_WETH,
      swapRouter: LOCAL_ROUTER,
      liquidityManager: LOCAL_LM,
      txnBot: LOCAL_TXNBOT_ENDPOINT,
      rpc: LOCAL_RPC_ENDPOINT,
    },
  },
  {
    // sepolia
    id: 11155111,
    graphql: env.VITE_PONDER_SEPOLIA ?? '',
    path: 'sepolia',
    stake: '0xCd21a41a137BCAf8743E47D048F57D92398f7Da9',
    harb: '0x087F256D11fe533b0c7d372e44Ee0F9e47C89dF9',
    uniswap: 'https://app.uniswap.org/swap?chain=mainnet&inputCurrency=NATIVE',
    cheats: null,
  },
  {
    // base-sepolia (local dev default)
    id: 84532,
    graphql: LOCAL_GRAPHQL_ENDPOINT,
    path: 'sepoliabase',
    stake: '0xe28020BCdEeAf2779dd47c670A8eFC2973316EE2',
    harb: '0x22c264Ecf8D4E49D1E3CabD8DD39b7C4Ab51C1B8',
    uniswap: 'https://app.uniswap.org/swap?chain=mainnet&inputCurrency=NATIVE',
    cheats: {
      weth: '0x4200000000000000000000000000000000000006',
      swapRouter: '0x94cC0AaC535CCDB3C01d6787D6413C739ae12bc4',
      txnBot: LOCAL_TXNBOT_ENDPOINT,
    },
  },
  {
    // base mainnet
    id: 8453,
    graphql: env.VITE_PONDER_BASE ?? '',
    path: 'base',
    stake: '0xed70707fab05d973ad41eae8d17e2bcd36192cfc',
    harb: '0x45caa5929f6ee038039984205bdecf968b954820',
    uniswap: 'https://app.uniswap.org/swap?chain=mainnet&inputCurrency=NATIVE',
    cheats: {
      weth: '0x4200000000000000000000000000000000000006',
      swapRouter: '',
      txnBot: env.VITE_TXNBOT_BASE ?? '',
    },
  },
];

export function getChain(id: number) {
  return chainsData.find(obj => obj.id === id);
}

export const enableLocalSwap = env.VITE_ENABLE_LOCAL_SWAP === 'true';
