import { getTokenAggregationApiBase } from '@/services/api/tokenAggregation'

export interface OfficialProtocolContractRow {
  name: string
  address: string
  inventoryKey?: string
  minCodeSize?: number
  notes?: string
}

export type ContractVerificationStatus = 'verified' | 'below_min' | 'no_code' | 'error'

export interface ContractVerificationRow {
  name: string
  address: string
  codeSize: number
  minCodeSize?: number
  status: ContractVerificationStatus
}

export interface ProtocolVerificationReport {
  verifiedAt: string
  chainId: number
  rpcUsed: boolean
  allVerified: boolean
  contracts: ContractVerificationRow[]
}

export interface OfficialProtocolRow {
  id: string
  classification?: string
  requiredForProduction?: boolean
  upstreamRepo?: string
  upstreamSubmodule?: string
  deployScripts?: string[]
  verifyScripts?: string[]
  deployMethod?: string
  integrationNotes?: string
  contracts: OfficialProtocolContractRow[]
}

export interface OfficialProtocolsResponse {
  generatedAt: string
  source: string
  chainId: number
  chainName?: string
  policyDoc?: string
  guardrails: string[]
  forbiddenProductionPatterns: Array<{ id: string; description: string }>
  count: number
  protocols: OfficialProtocolRow[]
  protocol?: OfficialProtocolRow
  verification?: ProtocolVerificationReport
  schemaVersion?: string
  updated?: string
}

export async function fetchOfficialProtocols(protocolId?: string): Promise<OfficialProtocolsResponse | null> {
  const base = `${getTokenAggregationApiBase()}/report/official-protocols`
  const url = protocolId ? `${base}/${encodeURIComponent(protocolId)}` : base
  try {
    const response = await fetch(url, { cache: 'no-store' })
    if (!response.ok) return null
    return (await response.json()) as OfficialProtocolsResponse
  } catch {
    return null
  }
}
