import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
import { dirname, join } from 'path';

export type OmnlPollerStateFile = {
  chains: Record<string, number>;
};

function statePath(): string {
  return process.env.OMNL_POLLER_STATE_PATH?.trim() || join(process.cwd(), '.omnl-poller-state.json');
}

export function loadLastProcessedBlock(chainId: number): number | null {
  const p = statePath();
  if (!existsSync(p)) return null;
  try {
    const j = JSON.parse(readFileSync(p, 'utf8')) as OmnlPollerStateFile;
    const v = j.chains?.[String(chainId)];
    return typeof v === 'number' && v >= 0 ? v : null;
  } catch {
    return null;
  }
}

export function saveLastProcessedBlock(chainId: number, block: number): void {
  const p = statePath();
  let j: OmnlPollerStateFile = { chains: {} };
  if (existsSync(p)) {
    try {
      const parsed = JSON.parse(readFileSync(p, 'utf8')) as OmnlPollerStateFile;
      j = { chains: { ...parsed.chains } };
    } catch {
      j = { chains: {} };
    }
  }
  j.chains[String(chainId)] = block;
  const dir = dirname(p);
  if (dir && dir !== '.') {
    mkdirSync(dir, { recursive: true });
  }
  writeFileSync(p, JSON.stringify(j, null, 2) + '\n', 'utf8');
}
