import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.38.4';

// === AI Hub routing (auto-injected) ===
const _HUB_KEY = Deno.env.get('AI_HUB_API_KEY') || '';
const _HUB_BASE = (Deno.env.get('AI_HUB_BASE_URL') || '').replace(/\/+$/, '');
const _USE_HUB = !!(_HUB_KEY && _HUB_BASE);
const _AI_CHAT_URL = _USE_HUB ? `${_HUB_BASE}/chat/completions` : _AI_CHAT_URL;
const _AI_CHAT_KEY = _USE_HUB ? _HUB_KEY : (Deno.env.get('LOVABLE_API_KEY') || '');
const _AI_CHAT_DEFAULT_MODEL = Deno.env.get('AI_HUB_DEFAULT_CHAT_MODEL') || 'agent-default';
const _mapAiModel = (m: string) => (_USE_HUB && /^(google|openai|anthropic)\//i.test(m || '')) ? _AI_CHAT_DEFAULT_MODEL : m;
// === end AI Hub routing ===


const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};

// ============================================================
// 系统文档生成器 - 供 GPT/Gemini 评估和审计
// ============================================================

// AI Agent 定义
const AI_AGENTS = {
  manager: {
    id: 'manager',
    name: '小管',
    role: '店铺经理',
    description: '店铺总负责人，统筹全局运营、跨部门协调和战略决策',
    specialties: ['店铺管理', '数据分析', '团队协作', '运营策略', '业务决策', 'KPI管理', '跨部门协调'],
    managedTables: ['goals', 'agent_settings', 'agent_roles'],
    edgeFunctions: ['manager-genui', 'manager-insights', 'admin-operations']
  },
  product: {
    id: 'product',
    name: '小品',
    role: '商品经理',
    description: '商品域专家，负责选品、定价、库存和品类管理',
    specialties: ['选品管理', '定价策略', '库存管理', '品类规划', '供应商关系', '商品上下架'],
    managedTables: ['products', 'categories', 'brands', 'category_brands'],
    edgeFunctions: ['product-genui', 'product-insights', 'product-operations']
  },
  marketing: {
    id: 'marketing',
    name: '小营',
    role: '营销经理',
    description: '营销域专家，负责活动策划、促销推广和用户增长',
    specialties: ['营销策划', '活动推广', '优惠券管理', '用户增长', '品牌推广'],
    managedTables: ['coupons', 'marketing_campaigns', 'flash_sales', 'group_buy_activities', 'payment_gifts', 'banners'],
    edgeFunctions: ['marketing-genui', 'marketing-insights', 'marketing-operations']
  },
  service: {
    id: 'service',
    name: '小服',
    role: '客服经理',
    description: '服务域专家，负责售后处理、客户满意度和投诉管理',
    specialties: ['售后服务', '订单查询', '退换货处理', '物流跟踪', '投诉处理'],
    managedTables: ['after_sales_requests', 'orders'],
    edgeFunctions: ['service-genui', 'service-insights', 'service-operations']
  },
  finance: {
    id: 'finance',
    name: '小财',
    role: '财务经理',
    description: '财务域专家，负责收支管理、财务分析和资金流转',
    specialties: ['收入分析', '成本核算', '利润管理', '资金流转', '财务报表'],
    managedTables: ['orders', 'balance_transactions', 'user_balances', 'recharge_plans'],
    edgeFunctions: ['finance-genui', 'finance-insights']
  }
};

// GenUI 组件定义
const GENUI_COMPONENTS = {
  display: [
    { type: 'stats_row', description: '统计指标行，展示多个KPI', props: ['items: StatItem[]', 'columns?: number'] },
    { type: 'data_table', description: '数据表格，支持分页和操作', props: ['columns: TableColumn[]', 'data: TableRow[]', 'actions?: ActionButton[]'] },
    { type: 'chart', description: '可视化图表', props: ['type: bar|line|pie|area', 'data: ChartDataPoint[]', 'title?: string'] },
    { type: 'progress_bar', description: '进度条，展示目标完成度', props: ['label: string', 'value: number', 'max: number'] },
    { type: 'text', description: '富文本块', props: ['content: string', 'variant?: h1|h2|h3|body|caption'] },
    { type: 'alert', description: '提示/警告框', props: ['type: info|warning|error|success', 'title: string', 'description?: string'] },
    { type: 'insight_card', description: 'AI洞察卡片', props: ['data: InsightData'] },
    { type: 'divider', description: '分隔线', props: ['margin?: sm|md|lg'] }
  ],
  action: [
    { type: 'action_buttons', description: '操作按钮组', props: ['buttons: ActionButton[]', 'layout?: horizontal|vertical'] },
    { type: 'approval_card', description: '审批卡片', props: ['data: ApprovalData', 'onApprove?: string', 'onReject?: string'] }
  ],
  agent: [
    { type: 'agent_status', description: 'Agent状态显示', props: ['agentType: string', 'status: string'] },
    { type: 'agent_capabilities', description: 'Agent能力列表', props: ['capabilities: string[]'] },
    { type: 'agent_thinking', description: 'Agent思考过程', props: ['steps: ThinkingStep[]'] },
    { type: 'agent_settings_card', description: 'Agent设置面板', props: ['agentType: string', 'settings: object'] }
  ],
  special: [
    { type: 'sandbox_result', description: '代码执行结果', props: ['result: SandboxExecutionResult'] },
    { type: 'container', description: '嵌套容器', props: ['children: UIComponent[]', 'layout?: vertical|horizontal|grid'] }
  ]
};

// 边缘函数列表
const EDGE_FUNCTIONS = [
  { name: 'system-info', method: 'GET', auth: false, description: '获取系统元数据、统计信息、能力定义' },
  { name: 'system-actions', method: 'GET', auth: false, description: '获取可执行操作定义' },
  { name: 'system-audit', method: 'POST', auth: false, description: '系统文档导出和AI审计' },
  { name: 'coze-langchain', method: 'POST', auth: true, description: 'LangChain Agent对话入口(SSE流式)' },
  { name: 'admin-operations', method: 'POST', auth: true, description: '通用管理操作执行' },
  { name: 'product-operations', method: 'POST', auth: true, description: '商品域CRUD操作' },
  { name: 'marketing-operations', method: 'POST', auth: true, description: '营销域活动操作' },
  { name: 'service-operations', method: 'POST', auth: true, description: '客服域售后操作' },
  { name: 'manager-genui', method: 'POST', auth: true, description: '店铺经理GenUI接口' },
  { name: 'product-genui', method: 'POST', auth: true, description: '商品经理GenUI接口' },
  { name: 'marketing-genui', method: 'POST', auth: true, description: '营销经理GenUI接口' },
  { name: 'service-genui', method: 'POST', auth: true, description: '客服经理GenUI接口' },
  { name: 'finance-genui', method: 'POST', auth: true, description: '财务经理GenUI接口' },
  { name: 'manager-insights', method: 'POST', auth: true, description: '经理AI洞察生成' },
  { name: 'product-insights', method: 'POST', auth: true, description: '商品AI洞察生成' },
  { name: 'marketing-insights', method: 'POST', auth: true, description: '营销AI洞察生成' },
  { name: 'service-insights', method: 'POST', auth: true, description: '客服AI洞察生成' },
  { name: 'finance-insights', method: 'POST', auth: true, description: '财务AI洞察生成' },
  { name: 'context-read', method: 'POST', auth: true, description: '读取Agent会话上下文' },
  { name: 'context-commit', method: 'POST', auth: true, description: '提交Agent上下文变更' },
  { name: 'coupon-management', method: 'POST', auth: true, description: '优惠券管理操作' },
  { name: 'order-query', method: 'POST', auth: true, description: '订单查询' },
  { name: 'brand-query', method: 'GET', auth: false, description: '品牌查询' },
  { name: 'agent-debug', method: 'POST', auth: true, description: 'Agent调试接口' },
  { name: 'agent-schema', method: 'GET', auth: false, description: 'Agent Schema定义' },
  { name: 'api-registry', method: 'GET', auth: false, description: 'API注册表' }
];

// 管理操作定义
const ADMIN_OPERATIONS = {
  product: {
    query: { description: '查询产品列表', params: ['keyword', 'category', 'brand', 'minPrice', 'maxPrice', 'isActive'] },
    create: { description: '创建新产品', params: ['name', 'price', 'description', 'category', 'brand', 'stock_quantity'] },
    update: { description: '更新产品信息', params: ['id', 'name', 'price', 'description', 'stock_quantity'] },
    delete: { description: '删除产品', params: ['id'] },
    updateStock: { description: '更新库存', params: ['id', 'quantity'] },
    toggleStatus: { description: '切换上下架状态', params: ['id', 'isActive'] }
  },
  order: {
    query: { description: '查询订单', params: ['orderNumber', 'userId', 'status', 'startDate', 'endDate'] },
    updateStatus: { description: '更新订单状态', params: ['id', 'status'] },
    addTracking: { description: '添加物流单号', params: ['id', 'tracking_number'] },
    cancel: { description: '取消订单', params: ['id', 'reason'] },
    refund: { description: '订单退款', params: ['id', 'amount', 'reason'] }
  },
  afterSales: {
    query: { description: '查询售后请求', params: ['orderNumber', 'userId', 'status', 'type'] },
    approve: { description: '批准售后', params: ['id', 'refund_amount', 'notes'] },
    reject: { description: '拒绝售后', params: ['id', 'reason'] }
  },
  coupon: {
    query: { description: '查询优惠券', params: ['keyword', 'status', 'type', 'scope'] },
    create: { description: '创建优惠券', params: ['name', 'code', 'type', 'discount_value', 'start_date', 'end_date'] },
    update: { description: '更新优惠券', params: ['id', 'name', 'status'] },
    delete: { description: '删除优惠券', params: ['id'] }
  },
  campaign: {
    query: { description: '查询营销活动', params: ['keyword', 'status', 'type'] },
    create: { description: '创建营销活动', params: ['name', 'description', 'type', 'start_date', 'end_date'] },
    approve: { description: '审批通过活动', params: ['id', 'review_notes'] },
    reject: { description: '审批拒绝活动', params: ['id', 'review_notes'] },
    pause: { description: '暂停活动', params: ['id'] },
    resume: { description: '恢复活动', params: ['id'] }
  },
  goal: {
    query: { description: '查询Agent目标', params: ['agent_type', 'status', 'priority'] },
    create: { description: '创建目标', params: ['title', 'description', 'agent_type', 'target_value', 'unit', 'deadline'] },
    update: { description: '更新目标进度', params: ['id', 'current_value', 'status'] }
  }
};

// 技术栈定义
const TECH_STACK = {
  frontend: {
    framework: 'React 18.3.1',
    buildTool: 'Vite',
    language: 'TypeScript 5.x',
    styling: 'Tailwind CSS 3.x',
    uiLibrary: 'shadcn/ui (Radix UI based)',
    stateManagement: 'TanStack Query 5.83',
    routing: 'React Router 6.30',
    charts: 'Recharts 2.15'
  },
  backend: {
    platform: 'Supabase',
    database: 'PostgreSQL 15',
    edgeFunctions: 'Deno Runtime',
    authentication: 'Supabase Auth (JWT)',
    storage: 'Supabase Storage',
    realtime: 'Supabase Realtime'
  },
  ai: {
    primaryAgent: 'Coze LangChain Agent',
    insightGeneration: 'Lovable AI Gateway',
    supportedModels: ['google/gemini-3-flash-preview', 'google/gemini-2.5-pro', 'openai/gpt-5']
  }
};

// 安全配置
const SECURITY_CONFIG = {
  authentication: {
    method: 'Supabase Auth with JWT',
    tokenRefresh: 'Automatic',
    sessionDuration: '1 week'
  },
  authorization: {
    roles: ['user', 'admin', 'super_admin'],
    rlsEnabled: true,
    policyStrategy: 'User owns data OR Admin access'
  },
  dataProtection: {
    transport: 'HTTPS/TLS',
    apiKeys: 'Stored in Supabase Secrets',
    sensitiveData: 'Server-side only'
  },
  auditTrail: {
    contextChanges: 'agent_context + context_changes tables',
    aiReadLog: 'ai_read_log table'
  }
};

// 审计提示词模板
const AUDIT_PROMPTS = {
  architecture: `你是一位资深的软件架构师，请评估以下电商管理系统的架构设计：

评估维度：
1. 模块划分是否合理
2. Agent职责边界是否清晰
3. 前后端分离是否得当
4. 扩展性和可维护性
5. 是否遵循最佳实践

请给出0-100的评分，列出发现的问题和改进建议。`,

  security: `你是一位安全专家，请审计以下系统的安全配置：

审计要点：
1. RLS策略是否完善
2. 认证授权是否安全
3. 敏感数据是否保护得当
4. API安全性
5. 潜在的安全漏洞

请给出0-100的评分，按严重程度列出安全问题和修复建议。`,

  code: `你是一位代码质量专家，请评估以下代码结构：

评估维度：
1. 代码组织是否清晰
2. 是否遵循DRY原则
3. 类型安全性
4. 错误处理
5. 可测试性

请给出0-100的评分，列出代码质量问题和重构建议。`,

  database: `你是一位数据库专家，请评估以下数据库设计：

评估维度：
1. 表结构是否规范
2. 关系设计是否合理
3. 索引是否优化
4. 状态机设计
5. 数据完整性约束

请给出0-100的评分，列出设计问题和优化建议。`,

  api: `你是一位API设计专家，请评估以下Edge Functions设计：

评估维度：
1. RESTful设计规范
2. 错误处理一致性
3. 性能考虑
4. 版本控制
5. 文档完整性

请给出0-100的评分，列出API设计问题和改进建议。`
};

// 生成完整系统文档
async function generateSystemDocumentation(supabase: any) {
  // 获取数据库统计
  const [
    productsCount, ordersCount, usersCount, afterSalesCount,
    couponsCount, campaignsCount, goalsCount
  ] = await Promise.all([
    supabase.from('products').select('*', { count: 'exact', head: true }),
    supabase.from('orders').select('*', { count: 'exact', head: true }),
    supabase.from('profiles').select('*', { count: 'exact', head: true }),
    supabase.from('after_sales_requests').select('*', { count: 'exact', head: true }),
    supabase.from('coupons').select('*', { count: 'exact', head: true }),
    supabase.from('marketing_campaigns').select('*', { count: 'exact', head: true }),
    supabase.from('goals').select('*', { count: 'exact', head: true })
  ]);

  return {
    version: '2.0.0',
    exportedAt: new Date().toISOString(),
    documentation: {
      overview: {
        name: '智能电商管理系统',
        description: 'AI驱动的多Agent协作电商管理平台',
        architecture: 'Multi-Agent + GenUI',
        coreFeatures: [
          '5个专业AI Agent协作管理',
          'GenUI动态组件渲染',
          '自然语言操作界面',
          '智能审批工作流',
          '实时数据分析和洞察生成'
        ]
      },
      
      techStack: TECH_STACK,
      
      agents: AI_AGENTS,
      
      genui: {
        description: 'Generative UI系统 - AI返回结构化UISchema，前端动态渲染',
        components: GENUI_COMPONENTS,
        renderFlow: [
          'AI返回UISchema JSON',
          'DynamicRenderer解析Schema',
          '查询componentRegistry获取组件',
          '递归渲染子组件',
          '绑定事件处理器'
        ]
      },
      
      database: {
        statistics: {
          products: productsCount.count || 0,
          orders: ordersCount.count || 0,
          users: usersCount.count || 0,
          afterSales: afterSalesCount.count || 0,
          coupons: couponsCount.count || 0,
          campaigns: campaignsCount.count || 0,
          goals: goalsCount.count || 0
        },
        tables: [
          { name: 'products', description: '商品表', agent: 'product', keyFields: ['name', 'price', 'stock_quantity', 'category', 'brand'] },
          { name: 'orders', description: '订单表', agent: 'service/finance', statusValues: ['pending', 'paid', 'shipped', 'completed', 'cancelled'] },
          { name: 'profiles', description: '用户表', roleValues: ['user', 'admin', 'super_admin'] },
          { name: 'after_sales_requests', description: '售后表', agent: 'service', typeValues: ['return', 'exchange', 'repair'] },
          { name: 'coupons', description: '优惠券表', agent: 'marketing', typeValues: ['percentage', 'fixed'] },
          { name: 'marketing_campaigns', description: '营销活动表', agent: 'marketing', createdByValues: ['manual', 'ai'] },
          { name: 'flash_sales', description: '秒杀活动表', agent: 'marketing' },
          { name: 'group_buy_activities', description: '拼团活动表', agent: 'marketing' },
          { name: 'goals', description: 'Agent目标表', agent: 'manager' },
          { name: 'agent_settings', description: 'Agent配置表', agent: 'manager' },
          { name: 'agent_context', description: 'Agent会话上下文', agent: 'all' },
          { name: 'context_changes', description: '上下文变更审计日志', agent: 'all' }
        ]
      },
      
      api: {
        edgeFunctions: EDGE_FUNCTIONS,
        operations: ADMIN_OPERATIONS
      },
      
      security: SECURITY_CONFIG,
      
      businessRules: {
        orderWorkflow: {
          states: ['pending', 'paid', 'shipped', 'completed', 'cancelled'],
          rules: [
            '发货时必须添加物流单号',
            '已发货后才能标记完成',
            '取消订单需要说明原因'
          ]
        },
        afterSalesWorkflow: {
          states: ['pending', 'processing', 'approved', 'rejected', 'completed'],
          rules: [
            '退款金额不能超过订单金额',
            '需要记录处理备注',
            '7天内必须处理'
          ]
        },
        campaignWorkflow: {
          states: ['draft', 'pending', 'active', 'paused', 'completed', 'rejected'],
          rules: [
            'AI创建的活动需要人工审核',
            '活动可以被暂停和恢复',
            '开始时间必须早于结束时间'
          ]
        },
        agentCollaboration: {
          rules: [
            'Manager可以协调所有Agent',
            '每个Agent专注自己的业务域',
            '跨域操作需通过Manager协调',
            '高风险操作需人工审批'
          ]
        }
      },
      
      codeStructure: {
        directories: [
          { path: 'src/ai/', description: 'AI相关模块(GenUI, Actions)' },
          { path: 'src/ai/genui/', description: 'GenUI渲染系统' },
          { path: 'src/ai/genui/components/', description: 'GenUI组件库' },
          { path: 'src/components/admin/', description: '管理后台组件' },
          { path: 'src/components/admin/marketing/', description: '营销模块' },
          { path: 'src/components/admin/products/', description: '商品模块' },
          { path: 'src/components/admin/finance/', description: '财务模块' },
          { path: 'src/components/admin/aftersales/', description: '售后模块' },
          { path: 'src/components/admin/manager/', description: '经理模块' },
          { path: 'src/components/admin/shared/', description: '共享组件' },
          { path: 'src/pages/', description: '页面组件' },
          { path: 'src/hooks/', description: '自定义Hooks' },
          { path: 'src/utils/', description: '工具函数' },
          { path: 'src/types/', description: '类型定义' },
          { path: 'supabase/functions/', description: 'Edge Functions' }
        ],
        keyFiles: [
          { path: 'src/ai/genui/DynamicRenderer.tsx', description: 'GenUI动态渲染器' },
          { path: 'src/ai/genui/registry.tsx', description: '组件注册表' },
          { path: 'src/ai/genui/types.ts', description: 'GenUI类型定义' },
          { path: 'src/types/agents.ts', description: 'Agent定义' },
          { path: 'src/utils/agentClient.ts', description: 'Agent通信客户端' },
          { path: 'supabase/functions/system-info/index.ts', description: '系统信息API' },
          { path: 'supabase/functions/coze-langchain/index.ts', description: 'LangChain Agent入口' }
        ]
      }
    }
  };
}

// 调用AI进行审计
async function performAIAudit(
  documentation: any,
  scope: string[],
  model: string,
  detailed: boolean
) {
  const LOVABLE_API_KEY = Deno.env.get("LOVABLE_API_KEY");
  if (!LOVABLE_API_KEY) {
    throw new Error("LOVABLE_API_KEY is not configured");
  }

  const findings: any[] = [];
  const categoryScores: Record<string, { score: number; findings: number }> = {};

  // 为每个审计范围调用AI
  for (const category of scope) {
    const prompt = AUDIT_PROMPTS[category as keyof typeof AUDIT_PROMPTS];
    if (!prompt) continue;

    const systemDoc = JSON.stringify({
      category,
      documentation: documentation.documentation
    }, null, 2);

    try {
      const response = await fetch(_AI_CHAT_URL, {
        method: "POST",
        headers: {
          "Authorization": `Bearer ${_AI_CHAT_KEY}`,
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          model: model === 'gpt-5' ? 'openai/gpt-5' : `google/${model}`,
          messages: [
            { role: "system", content: prompt },
            { role: "user", content: `请审计以下系统文档:\n\n${systemDoc}` }
          ],
          temperature: 0.3,
          max_tokens: 2000
        })
      });

      if (!response.ok) {
        const errorText = await response.text();
        console.error(`AI audit failed for ${category}:`, response.status, errorText);
        continue;
      }

      const result = await response.json();
      const content = result.choices?.[0]?.message?.content || '';
      
      // 解析AI响应提取评分和问题
      const scoreMatch = content.match(/评分[：:]\s*(\d+)/);
      const score = scoreMatch ? parseInt(scoreMatch[1]) : 75;
      
      // 提取问题列表
      const issueMatches = content.matchAll(/(\d+)\.\s*(.+?)(?=\n\d+\.|$)/gs);
      const categoryFindings: any[] = [];
      
      for (const match of issueMatches) {
        categoryFindings.push({
          id: `${category.toUpperCase()}_${categoryFindings.length + 1}`,
          category,
          severity: score < 60 ? 'high' : score < 80 ? 'medium' : 'low',
          title: match[2].substring(0, 100).trim(),
          description: match[2].trim(),
          rawContent: detailed ? match[0] : undefined
        });
      }

      findings.push(...categoryFindings);
      categoryScores[category] = {
        score,
        findings: categoryFindings.length
      };

    } catch (error) {
      console.error(`Error auditing ${category}:`, error);
    }
  }

  // 计算总体评分
  const scores = Object.values(categoryScores).map(c => c.score);
  const overallScore = scores.length > 0 
    ? Math.round(scores.reduce((a, b) => a + b, 0) / scores.length)
    : 0;

  return {
    auditId: crypto.randomUUID(),
    model,
    completedAt: new Date().toISOString(),
    summary: {
      overallScore,
      grade: overallScore >= 90 ? 'A' : overallScore >= 80 ? 'B' : overallScore >= 70 ? 'C' : overallScore >= 60 ? 'D' : 'F',
      categories: categoryScores,
      totalFindings: findings.length
    },
    findings: findings.slice(0, 50), // 限制返回数量
    recommendations: generateRecommendations(overallScore, categoryScores)
  };
}

// 生成改进建议
function generateRecommendations(overallScore: number, categories: Record<string, any>) {
  const recommendations: string[] = [];

  if (overallScore < 80) {
    recommendations.push('建议进行全面的代码审查和重构');
  }

  for (const [category, data] of Object.entries(categories)) {
    if (data.score < 70) {
      switch (category) {
        case 'architecture':
          recommendations.push('建议重新评估模块划分和依赖关系');
          break;
        case 'security':
          recommendations.push('优先修复安全漏洞，加强RLS策略');
          break;
        case 'code':
          recommendations.push('建议引入代码质量检查工具和测试覆盖');
          break;
        case 'database':
          recommendations.push('优化数据库索引和查询性能');
          break;
        case 'api':
          recommendations.push('统一API设计规范，完善错误处理');
          break;
      }
    }
  }

  return recommendations;
}

serve(async (req) => {
  if (req.method === 'OPTIONS') {
    return new Response(null, { headers: corsHeaders });
  }

  try {
    const supabase = createClient(
      Deno.env.get('SUPABASE_URL') ?? '',
      Deno.env.get('SUPABASE_ANON_KEY') ?? ''
    );

    const body = await req.json().catch(() => ({}));
    const { 
      action = 'export',
      scope = ['architecture', 'security', 'code', 'database', 'api'],
      model = 'gemini-3-flash-preview',
      detailed = false
    } = body;

    console.log(`system-audit called: action=${action}, scope=${scope.join(',')}, model=${model}`);

    // 生成系统文档
    const documentation = await generateSystemDocumentation(supabase);

    if (action === 'export') {
      // 仅导出文档
      return new Response(
        JSON.stringify(documentation, null, 2),
        { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    if (action === 'audit') {
      // 执行AI审计
      const auditResult = await performAIAudit(documentation, scope, model, detailed);
      
      return new Response(
        JSON.stringify({
          ...auditResult,
          documentation: detailed ? documentation : undefined
        }, null, 2),
        { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    return new Response(
      JSON.stringify({ error: 'Invalid action. Use "export" or "audit"' }),
      { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    );

  } catch (error) {
    console.error('system-audit error:', error);
    return new Response(
      JSON.stringify({ 
        error: (error instanceof Error ? error.message : 'Unknown error')
      }),
      { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    );
  }
});
