/**
 * Protocol version compatibility tracking.
 *
 * The Kraiken contract exposes a VERSION constant that must be checked
 * at runtime by indexers and frontends to ensure data compatibility.
 */

/**
 * Current version this library is built for.
 * Should match the deployed Kraiken contract VERSION.
 */
export const KRAIKEN_LIB_VERSION = 2;

/**
 * Singleton ID used for stack metadata rows across services.
 */
export const STACK_META_ID = 'stack-meta';

/**
 * List of Kraiken contract versions this library is compatible with.
 *
 * - Indexers MUST validate contract.VERSION is in this list at startup
 * - Frontends SHOULD validate indexer version matches KRAIKEN_LIB_VERSION
 *
 * Version History:
 * - v1: Initial deployment (30-tier TAX_RATES, index-based staking)
 * - v2: OptimizerV3, VWAP mirror floor, directional VWAP recording
 *
 * LiquidityManager event additions (no Kraiken VERSION bump):
 * - FeeDestinationSet(address indexed newDest) — emitted on every setFeeDestination() assignment
 * - FeeDestinationLocked(address indexed dest)  — emitted when the fee destination lock engages
 */
export const COMPATIBLE_CONTRACT_VERSIONS = [1, 2];

/**
 * Validates if a contract version is compatible with this library.
 */
export function isCompatibleVersion(contractVersion: number): boolean {
  return COMPATIBLE_CONTRACT_VERSIONS.includes(contractVersion);
}

/**
 * Error message generator for version mismatches.
 */
export function getVersionMismatchError(contractVersion: number, context: 'ponder' | 'frontend'): string {
  const compatibleVersions = COMPATIBLE_CONTRACT_VERSIONS.join(', ');
  const instructions =
    context === 'ponder'
      ? [
        '1. Check if contract was upgraded',
        '2. Update COMPATIBLE_CONTRACT_VERSIONS in kraiken-lib/src/version.ts',
        '3. Run: ./scripts/build-kraiken-lib.sh',
        '4. Run: rm -rf services/ponder/.ponder/',
        '5. Restart Ponder for full re-index',
      ]
      : [
        '1. Contact administrator - indexer may need updating',
        '2. Try refreshing the page',
        '3. Check if contract was recently upgraded',
      ];

  const lines = [
    '╔════════════════════════════════════════════════════════════╗',
    `║  ❌ CRITICAL: VERSION MISMATCH (${context})`.padEnd(61) + '║',
    '╠════════════════════════════════════════════════════════════╣',
    `║  Contract VERSION:      ${contractVersion}`.padEnd(61) + '║',
    `║  Library VERSION:       ${KRAIKEN_LIB_VERSION}`.padEnd(61) + '║',
    `║  Compatible versions:   ${compatibleVersions}`.padEnd(61) + '║',
    '║'.padEnd(61) + '║',
    '║  📋 Required Actions:'.padEnd(61) + '║',
    ...instructions.map(line => `║  ${line}`.padEnd(61) + '║'),
    '╚════════════════════════════════════════════════════════════╝',
  ];

  return lines.join('\n');
}
