// GET /components/:id — 取得零件最優版本合約
// GET /components/:id/versions — 取得所有版本清單（含評分）
// GET /components/search?q=... — 語意搜尋零件
// Requirements: 12.2, 12.3

import { Hono } from 'hono';
import type { Bindings } from '../types';
import { getComponent, getComponentVersions, searchComponents, toComponentRecord } from '../actions/queryComponents';
import type { ComponentRecord } from '../actions/queryComponents';

const app = new Hono<{ Bindings: Bindings }>();

// 全清單（t158 批次化）：/cypher/search discover 一次抓走整份目錄，
// 節點存在判定＋相似度全在 cypher 記憶體內比對——取代「每個 missing 節點
// 各打 1+8 次查詢」的疊爆模式（冷實例 8 節點實測 25.7s 的病根）。
// 也補上 CP2-B 記載的「registry 沒有列表端點」缺口。
// 必須在 /:id 之前，避免 "catalog" 被當作 id。
app.get('/catalog', async c => {
  const list = await c.env.SUBMISSIONS_KV.list({ prefix: 'comp:' });
  const seen = new Set<string>();
  const components: ComponentRecord[] = [];
  for (const key of list.keys) {
    const raw = await c.env.SUBMISSIONS_KV.get(key.name);
    if (!raw) continue;
    let v: Record<string, unknown>;
    try { v = JSON.parse(raw) as Record<string, unknown>; } catch { continue; }
    if (v.status === 'tombstone' || v.visibility !== 'public') continue;
    const dedup = `${String(v.component_hash_id ?? '')}:${String(v.version ?? '')}`;
    if (seen.has(dedup)) continue;
    seen.add(dedup);
    components.push(toComponentRecord(v));
  }
  return c.json({ success: true, data: { components, count: components.length } });
});

// 語意搜尋（必須在 /:id 之前，避免 "search" 被當作 id）
app.get('/search', async c => {
  const q = c.req.query('q');
  if (!q || q.trim() === '') {
    return c.json({ success: false, error: 'q 參數必填' }, 400);
  }

  const results = await searchComponents(q.trim(), c.env);
  return c.json({ success: true, data: { results, count: results.length } });
});

// 取得所有版本
app.get('/:id/versions', async c => {
  const id = c.req.param('id');
  const versions = await getComponentVersions(id, c.env);
  if (versions.length === 0) {
    return c.json({ success: false, error: `零件 ${id} 不存在` }, 404);
  }
  return c.json({ success: true, data: { versions, count: versions.length } });
});

// 取得最優版本
app.get('/:id', async c => {
  const id = c.req.param('id');
  const component = await getComponent(id, c.env);
  if (!component) {
    return c.json({ success: false, error: `零件 ${id} 不存在` }, 404);
  }
  return c.json({ success: true, data: component });
});

export default app;
