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

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

const SUPABASE_URL = 'https://tlsofopqzrzuduinsicm.supabase.co';
const BASE_URL = `${SUPABASE_URL}/functions/v1`;

/**
 * API 注册表 - 供后端 Agent 查看所有系统函数接口
 * 数据来源：数据库（动态）+ 静态补充
 * 公开端点，无需认证
 */
serve(async (req) => {
  if (req.method === 'OPTIONS') {
    return new Response(null, { headers: corsHeaders });
  }

  try {
    const url = new URL(req.url);
    const format = url.searchParams.get('format') || 'full'; // full | compact | grouped
    const category = url.searchParams.get('category'); // 筛选特定类别
    const source = url.searchParams.get('source') || 'hybrid'; // database | static | hybrid

    // 创建 Supabase 客户端
    const supabase = createClient(
      SUPABASE_URL,
      Deno.env.get('SUPABASE_ANON_KEY') || ''
    );

    let apis: any[] = [];
    let roles: any[] = [];
    let components: any[] = [];
    let dataSource = 'database';

    // 尝试从数据库读取
    if (source === 'database' || source === 'hybrid') {
      try {
        const [apisResult, rolesResult, componentsResult] = await Promise.all([
          supabase.from('api_registry').select('*').eq('is_active', true).order('display_order'),
          supabase.from('agent_roles').select('*').eq('is_active', true).order('display_order'),
          supabase.from('genui_components').select('*').eq('is_active', true).order('display_order')
        ]);

        if (!apisResult.error && apisResult.data?.length > 0) {
          apis = apisResult.data;
        }
        if (!rolesResult.error && rolesResult.data?.length > 0) {
          roles = rolesResult.data;
        }
        if (!componentsResult.error && componentsResult.data?.length > 0) {
          components = componentsResult.data;
        }

        console.log(`[api-registry] Database: APIs=${apis.length}, Roles=${roles.length}, Components=${components.length}`);
      } catch (dbError) {
        console.warn('[api-registry] Database read failed, using static fallback:', dbError);
        dataSource = 'static';
      }
    }

    // 如果数据库为空或明确要求静态，使用静态数据
    if (source === 'static' || (source === 'hybrid' && apis.length === 0)) {
      dataSource = 'static';
      apis = getStaticApis();
      roles = getStaticRoles();
      components = getStaticComponents();
    }

    // 按分类过滤
    if (category) {
      apis = apis.filter(api => api.category === category);
    }

    // 构建完整端点 URL
    const apisWithFullUrl = apis.map(api => ({
      ...api,
      full_url: api.endpoint?.startsWith('http') ? api.endpoint : `${SUPABASE_URL}${api.endpoint}`
    }));

    // 根据格式返回不同结构
    let responseData: any;

    switch (format) {
      case 'compact':
        responseData = {
          version: '2.0',
          source: dataSource,
          updated_at: new Date().toISOString(),
          apis: apisWithFullUrl.map(api => ({
            name: api.name,
            url: api.full_url,
            method: api.method,
            description: api.description
          })),
          roles: roles.map(role => ({
            id: role.role_id,
            name: role.name,
            capabilities: role.capabilities
          })),
          components: components.map(c => c.component_type)
        };
        break;

      case 'grouped':
        const groupedApis: Record<string, any[]> = {};
        apisWithFullUrl.forEach(api => {
          const cat = api.category || 'other';
          if (!groupedApis[cat]) groupedApis[cat] = [];
          groupedApis[cat].push(api);
        });

        const groupedComponents: Record<string, any[]> = {};
        components.forEach(comp => {
          const cat = comp.category || 'other';
          if (!groupedComponents[cat]) groupedComponents[cat] = [];
          groupedComponents[cat].push(comp);
        });

        responseData = {
          version: '2.0',
          source: dataSource,
          updated_at: new Date().toISOString(),
          apis: groupedApis,
          roles: roles,
          components: groupedComponents
        };
        break;

      default: // full
        responseData = {
          version: '2.0',
          source: dataSource,
          updated_at: new Date().toISOString(),
          system: {
            name: 'B2B电商AI管理系统',
            description: '支持多Agent协作的智能电商管理平台',
            base_url: SUPABASE_URL,
            functions_url: BASE_URL
          },
          apis: apisWithFullUrl,
          roles: roles,
          components: components,
          usage: {
            authentication: {
              description: '大部分接口需要 JWT 认证',
              header: 'Authorization: Bearer <your_jwt_token>',
              public_endpoints: apis.filter(a => !a.auth_required).map(a => a.name)
            },
            calling_example: {
              description: '调用示例',
              curl: `curl -X POST '${BASE_URL}/admin-operations' \\
  -H 'Authorization: Bearer <JWT>' \\
  -H 'Content-Type: application/json' \\
  -d '{"action": "getStats", "params": {}}'`
            },
            management: {
              description: '此注册表数据存储在数据库中，可通过管理后台动态更新',
              tables: ['api_registry', 'agent_roles', 'genui_components'],
              note: '新增功能后，在数据库中添加记录即可自动生效'
            }
          }
        };
    }

    console.log(`[api-registry] Response: format=${format}, category=${category || 'all'}, source=${dataSource}`);

    return new Response(JSON.stringify(responseData, null, 2), {
      headers: { ...corsHeaders, 'Content-Type': 'application/json' }
    });

  } catch (error) {
    console.error('[api-registry] Error:', error);
    return new Response(JSON.stringify({
      error: 'Failed to fetch API registry',
      message: ((error instanceof Error ? error.message : String(error)))
    }), {
      status: 500,
      headers: { ...corsHeaders, 'Content-Type': 'application/json' }
    });
  }
});

// ==================== 静态数据（后备） ====================

function getStaticApis(): any[] {
  return [
    { name: 'api-registry', category: 'admin', endpoint: '/functions/v1/api-registry', method: 'GET', description: 'API注册表查询（本接口）', auth_required: false, display_order: 0 },
    { name: 'system-info', category: 'admin', endpoint: '/functions/v1/system-info', method: 'GET', description: '系统信息查询', auth_required: false, display_order: 1 },
    { name: 'system-actions', category: 'admin', endpoint: '/functions/v1/system-actions', method: 'GET', description: '系统操作定义', auth_required: false, display_order: 2 },
    { name: 'agent-schema', category: 'admin', endpoint: '/functions/v1/agent-schema', method: 'GET', description: 'Agent Schema定义', auth_required: false, display_order: 3 },
    { name: 'admin-operations', category: 'admin', endpoint: '/functions/v1/admin-operations', method: 'POST', description: '管理后台通用操作', auth_required: true, display_order: 10 },
    { name: 'product-operations', category: 'product', endpoint: '/functions/v1/product-operations', method: 'POST', description: '商品管理操作', auth_required: true, display_order: 20 },
    { name: 'marketing-operations', category: 'marketing', endpoint: '/functions/v1/marketing-operations', method: 'POST', description: '营销活动操作', auth_required: true, display_order: 30 },
    { name: 'service-operations', category: 'service', endpoint: '/functions/v1/service-operations', method: 'POST', description: '售后服务操作', auth_required: true, display_order: 40 },
    { name: 'coupon-management', category: 'marketing', endpoint: '/functions/v1/coupon-management', method: 'POST', description: '优惠券管理', auth_required: true, display_order: 31 },
    { name: 'brand-query', category: 'product', endpoint: '/functions/v1/brand-query', method: 'POST', description: '品牌查询', auth_required: false, display_order: 21 },
    { name: 'order-query', category: 'service', endpoint: '/functions/v1/order-query', method: 'POST', description: '订单查询', auth_required: false, display_order: 41 },
    { name: 'service-query', category: 'service', endpoint: '/functions/v1/service-query', method: 'POST', description: '售后查询', auth_required: false, display_order: 42 },
    { name: 'coupon-query', category: 'marketing', endpoint: '/functions/v1/coupon-query', method: 'POST', description: '优惠券查询', auth_required: false, display_order: 32 },
    { name: 'intent-recognition', category: 'admin', endpoint: '/functions/v1/intent-recognition', method: 'POST', description: '意图识别', auth_required: false, display_order: 4 },
    { name: 'dify-chat', category: 'chat', endpoint: '/functions/v1/dify-chat', method: 'POST', description: 'Dify对话接口', auth_required: false, display_order: 50 },
    { name: 'dify-chat-admin', category: 'chat', endpoint: '/functions/v1/dify-chat-admin', method: 'POST', description: 'Dify管理端对话', auth_required: true, display_order: 51 },
    { name: 'marketing-genui', category: 'genui', endpoint: '/functions/v1/marketing-genui', method: 'POST', description: '营销GenUI接口', auth_required: true, display_order: 60 },
    { name: 'product-genui', category: 'genui', endpoint: '/functions/v1/product-genui', method: 'POST', description: '商品GenUI接口', auth_required: true, display_order: 61 },
    { name: 'finance-genui', category: 'genui', endpoint: '/functions/v1/finance-genui', method: 'POST', description: '财务GenUI接口', auth_required: true, display_order: 62 },
    { name: 'service-genui', category: 'genui', endpoint: '/functions/v1/service-genui', method: 'POST', description: '售后GenUI接口', auth_required: true, display_order: 63 },
    { name: 'manager-genui', category: 'genui', endpoint: '/functions/v1/manager-genui', method: 'POST', description: '总监GenUI接口', auth_required: true, display_order: 64 },
    { name: 'marketing-insights', category: 'insights', endpoint: '/functions/v1/marketing-insights', method: 'POST', description: '营销洞察', auth_required: true, display_order: 70 },
    { name: 'product-insights', category: 'insights', endpoint: '/functions/v1/product-insights', method: 'POST', description: '商品洞察', auth_required: true, display_order: 71 },
    { name: 'finance-insights', category: 'insights', endpoint: '/functions/v1/finance-insights', method: 'POST', description: '财务洞察', auth_required: true, display_order: 72 },
    { name: 'service-insights', category: 'insights', endpoint: '/functions/v1/service-insights', method: 'POST', description: '售后洞察', auth_required: true, display_order: 73 },
    { name: 'manager-insights', category: 'insights', endpoint: '/functions/v1/manager-insights', method: 'POST', description: '总监洞察', auth_required: true, display_order: 74 },
    { name: 'context-read', category: 'context', endpoint: '/functions/v1/context-read', method: 'POST', description: '读取上下文', auth_required: true, display_order: 80 },
    { name: 'context-commit', category: 'context', endpoint: '/functions/v1/context-commit', method: 'POST', description: '提交上下文', auth_required: true, display_order: 81 },
    { name: 'send-email', category: 'utility', endpoint: '/functions/v1/send-email', method: 'POST', description: '发送邮件', auth_required: false, display_order: 90 }
  ];
}

function getStaticRoles(): any[] {
  return [
    { role_id: 'manager', name: '运营总监', description: '统筹管理所有业务，制定目标，跨部门协调', capabilities: ['目标设定', '团队管理', '数据分析', '跨部门协调'], allowed_actions: ['admin-operations', 'manager-genui', 'system-info'], icon: 'Crown', color: 'gold', display_order: 0 },
    { role_id: 'marketing', name: '营销专员', description: '负责营销活动策划、优惠券管理、促销活动', capabilities: ['创建优惠券', '管理限时抢购', '设置拼团活动', '跨店联盟'], allowed_actions: ['marketing-operations', 'coupon-management', 'marketing-genui'], icon: 'Megaphone', color: 'orange', display_order: 1 },
    { role_id: 'product', name: '商品专员', description: '负责商品管理、库存监控、定价策略', capabilities: ['商品上下架', '库存管理', '价格调整', '商品推荐'], allowed_actions: ['product-operations', 'product-genui'], icon: 'Package', color: 'blue', display_order: 2 },
    { role_id: 'finance', name: '财务专员', description: '负责财务分析、交易审核、会员管理', capabilities: ['交易查询', '退款审批', '财务报表', '会员充值'], allowed_actions: ['admin-operations', 'finance-genui'], icon: 'DollarSign', color: 'green', display_order: 3 },
    { role_id: 'service', name: '售后专员', description: '负责售后处理、客诉跟进、退换货管理', capabilities: ['售后审批', '退款处理', '换货安排', '客诉跟进'], allowed_actions: ['service-operations', 'service-query', 'service-genui'], icon: 'HeadphonesIcon', color: 'purple', display_order: 4 }
  ];
}

function getStaticComponents(): any[] {
  return [
    { component_type: 'stats_row', name: '统计行', description: '展示关键指标统计', props_schema: { stats: { type: 'array', items: { label: 'string', value: 'string|number', trend: 'string' } } }, category: 'data', display_order: 1 },
    { component_type: 'data_table', name: '数据表格', description: '展示表格数据', props_schema: { columns: 'array', data: 'array', pagination: 'object' }, category: 'data', display_order: 2 },
    { component_type: 'chart', name: '图表', description: '数据可视化图表', props_schema: { chartType: 'line|bar|pie', data: 'array', config: 'object' }, category: 'chart', display_order: 3 },
    { component_type: 'insight_card', name: '洞察卡片', description: '展示AI分析洞察', props_schema: { title: 'string', content: 'string', type: 'info|warning|success', actions: 'array' }, category: 'display', display_order: 4 },
    { component_type: 'approval_card', name: '审批卡片', description: '待审批事项展示', props_schema: { title: 'string', description: 'string', actions: 'array', metadata: 'object' }, category: 'action', display_order: 5 },
    { component_type: 'action_buttons', name: '操作按钮组', description: '可执行的操作按钮', props_schema: { buttons: { type: 'array', items: { label: 'string', action: 'string', variant: 'string' } } }, category: 'action', display_order: 6 },
    { component_type: 'progress_bar', name: '进度条', description: '目标进度展示', props_schema: { label: 'string', current: 'number', target: 'number', unit: 'string' }, category: 'display', display_order: 7 },
    { component_type: 'text_block', name: '文本块', description: '富文本内容展示', props_schema: { content: 'string', format: 'markdown|plain' }, category: 'display', display_order: 8 },
    { component_type: 'alert_box', name: '提示框', description: '警告或提示信息', props_schema: { type: 'info|warning|error|success', title: 'string', message: 'string' }, category: 'display', display_order: 9 },
    { component_type: 'agent_settings', name: 'Agent设置', description: 'Agent配置面板', props_schema: { agentType: 'string', settings: 'object' }, category: 'action', display_order: 10 },
    { component_type: 'sandbox_result', name: '沙箱结果', description: '代码执行结果展示', props_schema: { stdout: 'string', stderr: 'string', artifacts: 'array' }, category: 'display', display_order: 11 }
  ];
}
