// 零件 metadata-only 索引：只寫 KV，不沙盒、不上 R2
// 用途：backfill 既有已部署但未索引的零件（cypher-executor 不從 R2 讀 wasm，零件用獨立 Worker URL）
// SDD: matrix/arcrun/.agents/specs/component-registry-canon/design.md Phase 1
//
// 跟 submitComponent 對照：
//   submitComponent  → 跑沙盒 + 寫 R2 + 寫 KV
//   indexOnlyComponent → 只寫 KV（hash_id 規則一致：cmp_ + sha256(canonical_id)[:8]）
//
// 冪等：相同 canonical_id + version 不重複寫

import type { ComponentContract, Bindings } from '../types';

async function deriveHashId(canonicalId: string): Promise<string> {
  const encoder = new TextEncoder();
  const data = encoder.encode(canonicalId);
  const hashBuffer = await crypto.subtle.digest('SHA-256', data);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  const hex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
  return 'cmp_' + hex.slice(0, 8);
}

export interface IndexOnlyResult {
  success: boolean;
  component_hash_id: string;
  canonical_id: string;
  version: string;
  already_indexed: boolean;
}

export async function indexOnlyComponent(
  contract: ComponentContract,
  env: Bindings,
): Promise<IndexOnlyResult> {
  const hashId = await deriveHashId(contract.canonical_id);
  const kvKey = `comp:${hashId}:${contract.version}`;

  const existing = await env.SUBMISSIONS_KV.get(kvKey);
  if (existing) {
    return {
      success: true,
      component_hash_id: hashId,
      canonical_id: contract.canonical_id,
      version: contract.version,
      already_indexed: true,
    };
  }

  const record = {
    component_hash_id: hashId,
    canonical_id: contract.canonical_id,
    display_name: contract.display_name,
    category: contract.category,
    version: contract.version,
    wasi_target: contract.wasi_target,
    stability: contract.stability,
    runtime_compat: contract.runtime_compat,
    component_type: contract.component_type ?? 'wasm',
    constraints: contract.constraints,
    input_schema: contract.input_schema,
    output_schema: contract.output_schema,
    gherkin_tests: contract.gherkin_tests,
    description: contract.description ?? '',
    aliases: contract.aliases ?? [],
    tags: contract.tags ?? [],
    success_rate: 1,
    avg_duration_ms: 0,
    call_count: 0,
    visibility: 'public' as const,
    status: 'active' as const,
    submitted_at: new Date().toISOString(),
    deprecated_at: null,
    indexed_only: true,
  };

  await env.SUBMISSIONS_KV.put(kvKey, JSON.stringify(record));
  await env.SUBMISSIONS_KV.put(`idx:${contract.canonical_id}`, hashId);

  return {
    success: true,
    component_hash_id: hashId,
    canonical_id: contract.canonical_id,
    version: contract.version,
    already_indexed: false,
  };
}
