/**
 * System Info Edge Function 测试
 * 验证系统信息API对AI Agent的可读性和完整性
 */
import "https://deno.land/std@0.224.0/dotenv/load.ts";
import { assertEquals, assertExists, assert } from "https://deno.land/std@0.224.0/assert/mod.ts";

const SUPABASE_URL = Deno.env.get("VITE_SUPABASE_URL")!;
const SUPABASE_ANON_KEY = Deno.env.get("VITE_SUPABASE_PUBLISHABLE_KEY")!;

const FUNCTION_URL = `${SUPABASE_URL}/functions/v1/system-info`;

interface SystemInfoResponse {
  version: string;
  description: string;
  systemIntroduction: {
    positioning: Record<string, unknown>;
    architecture: Record<string, unknown>;
    agentCollaboration: Record<string, unknown>;
    interactionParadigm: Record<string, unknown>;
    businessDomains: Record<string, unknown>;
    integrationGuide: Record<string, unknown>;
  };
  agents: Record<string, unknown>;
  genUIComponents: Record<string, unknown>;
  operations: Record<string, unknown>;
  relatedApis: Record<string, { url: string; description: string }>;
  apiTestExamples?: Record<string, unknown>;
}

// ========== 基础功能测试 ==========
Deno.test("system-info: GET请求应返回200", async () => {
  const response = await fetch(FUNCTION_URL, {
    headers: { 'apikey': SUPABASE_ANON_KEY },
  });
  const body = await response.json();
  assertEquals(response.status, 200);
  assertExists(body.version);
});

Deno.test("system-info: CORS预检应正常工作", async () => {
  const response = await fetch(FUNCTION_URL, { method: 'OPTIONS' });
  await response.text();
  assertEquals(response.status, 200);
});

// ========== AI Agent 可读性测试 ==========
Deno.test("system-info: 应包含系统完整说明", async () => {
  const response = await fetch(FUNCTION_URL, {
    headers: { 'apikey': SUPABASE_ANON_KEY },
  });
  const data: SystemInfoResponse = await response.json();
  
  assertExists(data.systemIntroduction);
  assertExists(data.systemIntroduction.positioning);
  assertExists(data.systemIntroduction.architecture);
  assertExists(data.systemIntroduction.agentCollaboration);
  assertExists(data.systemIntroduction.interactionParadigm);
  assertExists(data.systemIntroduction.integrationGuide);
});

Deno.test("system-info: 应包含5个Agent定义", async () => {
  const response = await fetch(FUNCTION_URL, {
    headers: { 'apikey': SUPABASE_ANON_KEY },
  });
  const data: SystemInfoResponse = await response.json();
  
  assertExists(data.agents);
  const agentKeys = Object.keys(data.agents);
  assert(agentKeys.includes('manager'), '应包含manager agent');
  assert(agentKeys.includes('product'), '应包含product agent');
  assert(agentKeys.includes('marketing'), '应包含marketing agent');
  assert(agentKeys.includes('service'), '应包含service agent');
  assert(agentKeys.includes('finance'), '应包含finance agent');
});

Deno.test("system-info: 每个Agent应有完整属性", async () => {
  const response = await fetch(FUNCTION_URL, {
    headers: { 'apikey': SUPABASE_ANON_KEY },
  });
  const data: SystemInfoResponse = await response.json();
  
  for (const [key, agent] of Object.entries(data.agents)) {
    const a = agent as Record<string, unknown>;
    assertExists(a.id, `Agent ${key} 应有id`);
    assertExists(a.name, `Agent ${key} 应有name`);
    assertExists(a.role, `Agent ${key} 应有role`);
    assertExists(a.description, `Agent ${key} 应有description`);
    assertExists(a.specialties, `Agent ${key} 应有specialties`);
    assertExists(a.keywords, `Agent ${key} 应有keywords`);
    assertExists(a.managedTables, `Agent ${key} 应有managedTables`);
  }
});

// ========== GenUI 组件定义测试 ==========
Deno.test("system-info: 应包含GenUI组件分类", async () => {
  const response = await fetch(FUNCTION_URL, {
    headers: { 'apikey': SUPABASE_ANON_KEY },
  });
  const data: SystemInfoResponse = await response.json();
  
  assertExists(data.genUIComponents);
  const components = data.genUIComponents as Record<string, unknown[]>;
  
  assertExists(components.display, '应有display类组件');
  assertExists(components.action, '应有action类组件');
  assertExists(components.agent, '应有agent类组件');
  assertExists(components.special, '应有special类组件');
});

Deno.test("system-info: 每个组件应有type/name/description/props", async () => {
  const response = await fetch(FUNCTION_URL, {
    headers: { 'apikey': SUPABASE_ANON_KEY },
  });
  const data: SystemInfoResponse = await response.json();
  
  const components = data.genUIComponents as Record<string, unknown[]>;
  
  for (const [category, items] of Object.entries(components)) {
    for (const item of items) {
      const c = item as Record<string, unknown>;
      assertExists(c.type, `${category}组件应有type`);
      assertExists(c.name, `${category}组件应有name`);
      assertExists(c.description, `${category}组件应有description`);
      assertExists(c.props, `${category}组件应有props`);
    }
  }
});

// ========== 操作定义测试 ==========
Deno.test("system-info: 应包含完整操作定义", async () => {
  const response = await fetch(FUNCTION_URL, {
    headers: { 'apikey': SUPABASE_ANON_KEY },
  });
  const data: SystemInfoResponse = await response.json();
  
  assertExists(data.operations);
  const ops = data.operations as Record<string, unknown>;
  
  assert(Object.keys(ops).length >= 8, '应有至少8个操作域');
  assertExists(ops.product, '应有product操作');
  assertExists(ops.order, '应有order操作');
  assertExists(ops.coupon, '应有coupon操作');
  assertExists(ops.campaign, '应有campaign操作');
});

// ========== 关联API测试 ==========
Deno.test("system-info: 应包含5个GenUI端点URL", async () => {
  const response = await fetch(FUNCTION_URL, {
    headers: { 'apikey': SUPABASE_ANON_KEY },
  });
  const data: SystemInfoResponse = await response.json();
  
  assertExists(data.relatedApis);
  assertExists(data.relatedApis['manager-genui']);
  assertExists(data.relatedApis['product-genui']);
  assertExists(data.relatedApis['marketing-genui']);
  assertExists(data.relatedApis['service-genui']);
  assertExists(data.relatedApis['finance-genui']);
  
  // 验证URL格式
  for (const [key, api] of Object.entries(data.relatedApis)) {
    if (key.endsWith('-genui')) {
      assert(api.url.includes('/functions/v1/'), `${key} URL应包含/functions/v1/`);
      assertExists(api.description, `${key} 应有description`);
    }
  }
});

// ========== AI Agent 调用示例测试 ==========
Deno.test("system-info: 应包含API测试示例（供AI Agent参考）", async () => {
  const response = await fetch(FUNCTION_URL, {
    headers: { 'apikey': SUPABASE_ANON_KEY },
  });
  const data: SystemInfoResponse = await response.json();
  
  // apiTestExamples 是新增的，验证其存在（如果已添加）
  if (data.apiTestExamples) {
    assert(Object.keys(data.apiTestExamples).length > 0, '应有测试示例');
  }
});

// ========== 集成指南测试 ==========
Deno.test("system-info: 集成指南应包含步骤说明", async () => {
  const response = await fetch(FUNCTION_URL, {
    headers: { 'apikey': SUPABASE_ANON_KEY },
  });
  const data: SystemInfoResponse = await response.json();
  
  const guide = data.systemIntroduction.integrationGuide as {
    forExternalAI?: {
      steps?: unknown[];
      endpoints?: Record<string, string>;
    };
    bestPractices?: string[];
  };
  
  assertExists(guide.forExternalAI);
  assertExists(guide.forExternalAI.steps);
  assertExists(guide.forExternalAI.endpoints);
  assert(Array.isArray(guide.bestPractices), '应有最佳实践列表');
});
