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';

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

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

// ========== GenUI 组件定义 ==========
const GENUI_COMPONENTS = {
  display: [
    { type: 'stats_row', name: '统计行', description: '展示多个统计指标', props: ['items: {label, value, change?, trend?}[]'] },
    { type: 'data_table', name: '数据表格', description: '展示结构化数据', props: ['columns: {key, label}[]', 'data: object[]', 'actions?: string[]'] },
    { type: 'chart', name: '图表', description: '可视化数据图表', props: ['type: line|bar|pie|area', 'data: array', 'title?: string'] },
    { type: 'progress_bar', name: '进度条', description: '目标进度展示', props: ['label: string', 'current: number', 'target: number', 'unit?: string'] },
    { type: 'text', name: '文本块', description: '富文本内容展示', props: ['content: string', 'format?: markdown|plain'] },
    { type: 'alert', name: '提示框', description: '警告或提示信息', props: ['type: info|warning|error|success', 'title: string', 'message: string'] },
    { type: 'insight_card', name: '洞察卡片', description: '展示AI分析洞察', props: ['title: string', 'content: string', 'type?: info|warning|success', 'actions?: array'] },
    { type: 'divider', name: '分隔线', description: '内容分隔', props: ['margin?: sm|md|lg'] }
  ],
  action: [
    { type: 'action_buttons', name: '操作按钮组', description: '可执行的操作按钮', props: ['buttons: {label, action, variant?, params?}[]'] },
    { type: 'approval_card', name: '审批卡片', description: '待审批事项展示', props: ['title: string', 'description: string', 'actions: array', 'metadata?: object'] }
  ],
  agent: [
    { type: 'agent_status', name: 'Agent状态', description: '显示Agent当前状态', props: ['agentType: string', 'status: string', 'message?: string'] },
    { type: 'agent_capabilities', name: 'Agent能力', description: '展示Agent可执行的能力列表', props: ['capabilities: string[]'] },
    { type: 'agent_thinking', name: 'Agent思考', description: '展示Agent思考过程', props: ['steps: {title, status, detail?}[]'] },
    { type: 'agent_settings_card', name: 'Agent设置卡片', description: 'Agent配置面板', props: ['agentType: string', 'settings: object'] },
    { type: 'agent_settings_list', name: 'Agent设置列表', description: '多个Agent的设置列表', props: ['agents: array'] }
  ],
  special: [
    { type: 'sandbox_result', name: '沙箱结果', description: '代码执行结果展示', props: ['result: object', 'showRerun?: boolean', 'showCancel?: boolean'] },
    { type: 'container', name: '容器', description: '嵌套多个组件', props: ['children: ComponentBlock[]', 'layout?: vertical|horizontal|grid'] }
  ]
};

// ========== 管理操作定义 ==========
const ADMIN_OPERATIONS = {
  product: {
    query: { name: '查询产品', description: '根据条件查询产品列表', params: ['keyword', 'category', 'brand', 'minPrice', 'maxPrice', 'isActive'] },
    create: { name: '创建产品', description: '创建新产品', params: ['name', 'price', 'description', 'category', 'brand', 'stock_quantity'] },
    update: { name: '更新产品', description: '更新产品信息', params: ['id', 'name', 'price', 'description', 'category', 'brand', 'stock_quantity'] },
    delete: { name: '删除产品', description: '删除产品', params: ['id'] },
    updateStock: { name: '更新库存', description: '更新产品库存数量', params: ['id', 'quantity'] },
    updatePrice: { name: '更新价格', description: '更新产品价格', params: ['id', 'price'] },
    toggleStatus: { name: '切换状态', description: '切换产品上架/下架状态', params: ['id', 'isActive'] }
  },
  order: {
    query: { name: '查询订单', description: '根据条件查询订单列表', params: ['orderNumber', 'userId', 'status', 'startDate', 'endDate'] },
    update: { name: '更新订单', description: '更新订单信息', params: ['id', 'status', 'notes', 'tracking_number'] },
    updateStatus: { name: '更新订单状态', description: '更新订单状态', params: ['id', 'status'] },
    addTracking: { name: '添加物流信息', description: '为订单添加物流跟踪号', params: ['id', 'tracking_number'] },
    cancel: { name: '取消订单', description: '取消订单', params: ['id', 'reason'] },
    refund: { name: '退款', description: '处理订单退款', params: ['id', 'amount', 'reason'] }
  },
  user: {
    query: { name: '查询用户', description: '根据条件查询用户列表', params: ['keyword', 'role', 'isActive'] },
    update: { name: '更新用户', description: '更新用户信息', params: ['id', 'display_name', 'phone', 'bio'] },
    updateRole: { name: '更新用户角色', description: '更新用户角色', params: ['id', 'role'] }
  },
  afterSales: {
    query: { name: '查询售后', description: '根据条件查询售后请求', params: ['orderNumber', 'userId', 'status', 'type'] },
    update: { name: '更新售后', description: '更新售后请求信息', params: ['id', 'status', 'admin_notes', 'refund_amount'] },
    approve: { name: '批准售后', description: '批准售后请求', params: ['id', 'refund_amount', 'notes'] },
    reject: { name: '拒绝售后', description: '拒绝售后请求', params: ['id', 'reason'] }
  },
  category: {
    query: { name: '查询分类', description: '查询商品分类列表', params: ['keyword', 'isActive'] },
    create: { name: '创建分类', description: '创建新分类', params: ['name', 'description', 'parent_id'] },
    update: { name: '更新分类', description: '更新分类信息', params: ['id', 'name', 'description', 'is_active'] },
    delete: { name: '删除分类', description: '删除分类', params: ['id'] }
  },
  brand: {
    query: { name: '查询品牌', description: '查询品牌列表', params: ['keyword', 'isActive'] },
    create: { name: '创建品牌', description: '创建新品牌', params: ['name', 'description', 'logo_url'] },
    update: { name: '更新品牌', description: '更新品牌信息', params: ['id', 'name', 'description', 'is_active'] },
    delete: { name: '删除品牌', description: '删除品牌', params: ['id'] }
  },
  banner: {
    query: { name: '查询横幅', description: '查询横幅列表', params: ['isActive'] },
    create: { name: '创建横幅', description: '创建新横幅', params: ['title', 'subtitle', 'image_url', 'link_url', 'button_text'] },
    update: { name: '更新横幅', description: '更新横幅信息', params: ['id', 'title', 'subtitle', 'is_active'] },
    delete: { name: '删除横幅', description: '删除横幅', params: ['id'] }
  },
  coupon: {
    query: { name: '查询优惠券', description: '查询优惠券列表', params: ['keyword', 'status', 'type', 'scope'] },
    create: { name: '创建优惠券', description: '创建新优惠券', params: ['name', 'code', 'type', 'discount_value', 'start_date', 'end_date', 'total_quantity', 'min_purchase_amount', 'max_discount_amount', 'per_user_limit', 'scope', 'description'] },
    update: { name: '更新优惠券', description: '更新优惠券信息', params: ['id', 'name', 'status', 'description'] },
    delete: { name: '删除优惠券', description: '删除优惠券', params: ['id'] }
  },
  campaign: {
    query: { name: '查询营销活动', description: '查询营销活动列表', params: ['keyword', 'status', 'type', 'created_by', 'startDate', 'endDate'] },
    create: { name: '创建营销活动', description: '创建新营销活动', params: ['name', 'description', 'type', 'start_date', 'end_date', 'status', 'config', 'ai_strategy', 'related_coupon_id'] },
    update: { name: '更新营销活动', description: '更新营销活动信息', params: ['id', 'name', 'description', 'status', 'config', 'review_notes'] },
    delete: { name: '删除营销活动', description: '删除营销活动', params: ['id'] },
    approve: { name: '审核通过', description: '审核通过营销活动', params: ['id', 'review_notes'] },
    reject: { name: '审核拒绝', description: '审核拒绝营销活动', params: ['id', 'review_notes'] },
    pause: { name: '暂停活动', description: '暂停营销活动', params: ['id'] },
    resume: { name: '恢复活动', description: '恢复营销活动', params: ['id'] }
  },
  flashSale: {
    query: { name: '查询秒杀活动', description: '查询秒杀活动列表', params: ['status', 'product_id'] },
    create: { name: '创建秒杀', description: '创建秒杀活动', params: ['name', 'product_id', 'flash_price', 'stock_limit', 'start_time', 'end_time'] },
    update: { name: '更新秒杀', description: '更新秒杀活动', params: ['id', 'status', 'flash_price', 'stock_limit'] }
  },
  groupBuy: {
    query: { name: '查询拼团活动', description: '查询拼团活动列表', params: ['status', 'product_id'] },
    create: { name: '创建拼团', description: '创建拼团活动', params: ['name', 'product_id', 'group_price', 'min_group_size', 'max_group_size', 'duration_hours'] }
  },
  goal: {
    query: { name: '查询目标', description: '查询Agent目标列表', params: ['agent_type', 'status', 'priority'] },
    create: { name: '创建目标', description: '创建新目标', params: ['title', 'description', 'agent_type', 'target_value', 'unit', 'deadline'] },
    update: { name: '更新目标', description: '更新目标进度', params: ['id', 'current_value', 'status'] }
  }
};

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 [
      productsCount, ordersCount, usersCount, afterSalesCount, 
      couponsCount, campaignsCount, flashSalesCount, groupBuyCount, 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('flash_sales').select('*', { count: 'exact', head: true }),
      supabase.from('group_buy_activities').select('*', { count: 'exact', head: true }),
      supabase.from('goals').select('*', { count: 'exact', head: true })
    ]);

    // 获取一些示例数据
    const [productsData, ordersData, categoriesData, brandsData, couponsData, campaignsData] = await Promise.all([
      supabase.from('products').select('id, name, price, stock_quantity, category, brand, is_active').limit(5),
      supabase.from('orders').select('id, order_number, status, total_amount, created_at').limit(5),
      supabase.from('categories').select('id, name, is_active').limit(10),
      supabase.from('brands').select('id, name, is_active').limit(10),
      supabase.from('coupons').select('id, name, code, type, discount_value, status, start_date, end_date').limit(5),
      supabase.from('marketing_campaigns').select('id, name, type, status, start_date, end_date, created_by, ai_strategy').limit(5)
    ]);

    // 获取活动统计
    const now = new Date().toISOString();
    const [activeCampaigns, upcomingCampaigns, pendingAfterSales] = await Promise.all([
      supabase.from('marketing_campaigns').select('*', { count: 'exact', head: true }).eq('status', 'active').lte('start_date', now).gte('end_date', now),
      supabase.from('marketing_campaigns').select('*', { count: 'exact', head: true }).eq('status', 'active').gt('start_date', now),
      supabase.from('after_sales_requests').select('*', { count: 'exact', head: true }).eq('status', 'pending')
    ]);

    const baseUrl = Deno.env.get('SUPABASE_URL');
    
    const systemInfo = {
      version: '3.1.0',
      description: '智能电商管理系统 - 支持 Lovable + Coze 协同开发的多Agent平台 (Coze请读取 collaborationProtocol.genUIContract 获取完整规范)',
      lastUpdated: new Date().toISOString(),

      // ========== Lovable-Coze 协同开发协议 ==========
      collaborationProtocol: {
        version: '1.0.0',
        description: 'Lovable AI 与 Coze LangChain Agent 的协同开发规范',
        
        // 角色分工
        roleAssignment: {
          lovableAI: {
            name: 'Lovable AI',
            responsibilities: [
              '代码实现和重构',
              '数据库迁移和 Schema 设计',
              '前端组件开发',
              'Edge Function 开发和部署',
              '测试和验证',
              '系统架构文档维护'
            ],
            communicationChannel: '通过 system-info API 发布系统规范变更'
          },
          cozeAgent: {
            name: 'Coze LangChain Agent',
            responsibilities: [
              '自然语言意图理解',
              '多轮对话上下文管理',
              'GenUI Schema 生成',
              '业务逻辑推理',
              '用户交互响应'
            ],
            communicationChannel: '通过 coze-langchain Edge Function 接收请求和规范'
          }
        },

        // 共享知识库
        sharedKnowledge: {
          systemInfo: {
            endpoint: '/functions/v1/system-info',
            purpose: '系统能力、组件库、数据模型的完整定义',
            refreshStrategy: 'Coze 应在每次会话开始时读取最新版本'
          },
          agentContext: {
            table: 'agent_context',
            purpose: '共享会话状态和业务上下文',
            fields: ['session_id', 'conversation_context', 'domain_context', 'selected_items']
          },
          systemGuide: {
            table: 'system_guide',
            purpose: '系统技术规范文档 (冻结的架构规范)',
            versionField: 'version'
          }
        },

        // GenUI Schema 规范
        genUIContract: {
          description: 'Coze 生成的 UI Schema 必须遵循此规范',
          
          // ⚠️ 核心响应格式 - Coze 必须返回此 JSON 结构
          requiredResponseFormat: {
            answer: 'string - 必填，简洁的文字回答（显示在聊天框）',
            agent_type: 'string - 必填，值为 manager|product|marketing|finance|service',
            ui_schema: {
              layout: 'vertical',
              gap: 'md',
              components: '[{ type: string, props: object }] - 组件数组'
            },
            suggested_actions: 'string[] - 可选，建议的后续操作按钮'
          },
          
          // ⚠️ 组件速查表 - Coze 必须使用这些组件类型
          componentQuickReference: {
            stats_row: {
              description: '统计指标行',
              requiredProps: { items: '[{label: string, value: string, trend?: string, icon?: string}]' },
              example: '{ "type": "stats_row", "props": { "items": [{"label": "总客户", "value": "156", "trend": "+12%"}] } }'
            },
            data_table: {
              description: '数据表格',
              requiredProps: { 
                title: 'string',
                columns: '[{key: string, label: string}]',
                rows: '[object]'
              },
              example: '{ "type": "data_table", "props": { "title": "客户列表", "columns": [{"key": "name", "label": "姓名"}], "rows": [{"name": "张三"}] } }'
            },
            chart: {
              description: '图表',
              requiredProps: {
                chartType: 'pie | bar | line | area',
                data: '[{name: string, value: number}]'
              },
              example: '{ "type": "chart", "props": { "chartType": "pie", "data": [{"name": "A", "value": 100}] } }'
            },
            alert: {
              description: '警告提示',
              requiredProps: {
                type: 'info | warning | error | success',
                message: 'string'
              },
              example: '{ "type": "alert", "props": { "type": "warning", "message": "库存不足" } }'
            },
            insight_card: {
              description: '洞察卡片',
              requiredProps: { title: 'string', description: 'string' },
              example: '{ "type": "insight_card", "props": { "title": "销售趋势", "description": "本周环比增长15%" } }'
            },
            progress_bar: {
              description: '进度条',
              requiredProps: { label: 'string', value: 'number (0-100)' },
              example: '{ "type": "progress_bar", "props": { "label": "目标完成度", "value": 75 } }'
            },
            text: {
              description: '文本块',
              requiredProps: { content: 'string' },
              example: '{ "type": "text", "props": { "content": "这是一段说明文字" } }'
            },
            approval_list: {
              description: '审批列表',
              requiredProps: { items: '[{id, title, description, status, created_at}]' },
              example: '{ "type": "approval_list", "props": { "items": [{"id": "1", "title": "活动审批", "status": "pending"}] } }'
            }
          },
          
          // ⚠️ 意图到 Agent 映射 - Coze 必须根据用户意图设置正确的 agent_type
          intentAgentMapping: {
            manager: {
              keywords: ['客户', '用户列表', '审批', '团队', 'KPI', '全局', '总览', '跨部门'],
              navigateTo: 'home Tab'
            },
            product: {
              keywords: ['商品', '库存', '上架', '热销', '品牌', '分类', '缺货'],
              navigateTo: 'products Tab'
            },
            marketing: {
              keywords: ['营销', '促销', '优惠券', '秒杀', '拼团', '活动', 'ROI'],
              navigateTo: 'marketing Tab'
            },
            finance: {
              keywords: ['财务', '收入', '利润', '退款', '会员', '报表', '销售额'],
              navigateTo: 'finance Tab'
            },
            service: {
              keywords: ['售后', '客服', '工单', '投诉', '物流', '退换货'],
              navigateTo: 'aftersales Tab'
            }
          },

          // ⚠️ 正确示例
          correctExample: {
            userInput: '查看客户信息列表',
            cozeResponse: {
              answer: '已为您查询到客户信息列表。',
              agent_type: 'manager',
              ui_schema: {
                layout: 'vertical',
                gap: 'md',
                components: [
                  {
                    type: 'stats_row',
                    props: {
                      items: [
                        { label: '总客户数', value: '156', trend: '+12%' },
                        { label: '活跃客户', value: '89', trend: '+5%' }
                      ]
                    }
                  },
                  {
                    type: 'data_table',
                    props: {
                      title: '客户信息列表',
                      columns: [
                        { key: 'name', label: '客户名称' },
                        { key: 'email', label: '邮箱' },
                        { key: 'phone', label: '电话' }
                      ],
                      rows: [
                        { name: '张三', email: 'zhang@example.com', phone: '138****1234' }
                      ]
                    }
                  }
                ]
              },
              suggested_actions: ['导出客户列表', '添加新客户']
            }
          },

          // ⚠️ 错误示例 - Coze 必须避免
          wrongExamples: [
            {
              error: '缺少 props 包装',
              wrong: '{ "type": "stats_row", "items": [...] }',
              correct: '{ "type": "stats_row", "props": { "items": [...] } }'
            },
            {
              error: 'title 在顶层而非 props 内',
              wrong: '{ "type": "data_table", "title": "标题", "props": { "columns": [...] } }',
              correct: '{ "type": "data_table", "props": { "title": "标题", "columns": [...] } }'
            },
            {
              error: '将 JSON 作为 Markdown 代码块返回',
              wrong: '```json\\n{"answer": "..."}\\n```',
              correct: '直接返回 JSON 对象，无 Markdown 包装'
            }
          ],

          componentRules: [
            '每个组件必须有 type 和 props 两个字段',
            '所有属性必须放在 props 内部，不能放在顶层',
            'type 必须是 validComponentTypes 中的值',
            '返回纯 JSON，不要用 Markdown 代码块包装'
          ],
          validComponentTypes: [
            'stats_row', 'data_table', 'chart', 'alert', 'insight_card',
            'progress_bar', 'text', 'divider', 'container', 'action_buttons',
            'approval_card', 'insight_feed', 'approval_list',
            'agent_status', 'agent_capabilities', 'agent_thinking'
          ]
        },

        // 数据上下文注入规范
        dataContextInjection: {
          description: 'coze-langchain Edge Function 会根据意图自动注入相关数据',
          injectionStrategy: {
            manager: ['orders_stats', 'products_stats', 'user_profiles', 'pending_approvals'],
            product: ['low_stock_products', 'hot_products', 'category_stats'],
            marketing: ['active_campaigns', 'coupons', 'sales_stats'],
            finance: ['revenue_stats', 'order_status_distribution', 'recharge_plans'],
            service: ['pending_aftersales', 'order_tracking', 'complaint_stats']
          },
          format: 'Markdown 文本格式，作为 LLM Prompt 的一部分注入'
        },

        // 变更通知机制
        changeNotification: {
          description: 'Lovable 修改系统后如何通知 Coze',
          mechanism: [
            'system-info.version 字段更新表示有重大变更',
            'Coze 可缓存 system-info，但应定期刷新（建议每小时）',
            '组件库变更会同步更新 GENUI_COMPONENT_LIBRARY prompt'
          ],
          currentVersion: '3.1.0'
        },

        // 错误处理约定
        errorHandling: {
          cozeFailure: 'coze-langchain 函数会自动降级到 Lovable AI Gateway',
          schemaError: 'DynamicRenderer 会自动 normalize 格式错误的 Schema',
          dataError: '数据获取失败时返回文本回复，不返回 ui_schema'
        },

        // API 端点
        apiEndpoint: {
          url: 'https://tlsofopqzrzuduinsicm.supabase.co/functions/v1/coze-langchain',
          method: 'POST',
          requestBody: {
            text: 'string - 用户输入的自然语言',
            agent_type: 'string - 可选，不传则自动识别',
            session_id: 'string - 可选，用于上下文关联'
          },
          responseProcessing: {
            answer: '→ 显示在聊天框',
            ui_schema: '→ 推送到工作台渲染',
            agent_type: '→ 决定导航到哪个 Tab'
          }
        }
      },
      
      // ========== 系统完整说明（供AI理解） ==========
      systemIntroduction: {
        // 系统定位
        positioning: {
          name: '智能电商管理系统 (Intelligent E-commerce Management System)',
          shortName: 'IEMS',
          purpose: '通过多AI Agent协作，实现电商运营的智能化、自动化管理',
          targetUsers: [
            'AI Agent（LangChain/Coze/Dify等）- 作为后端对接方',
            '电商运营人员 - 通过自然语言与AI交互完成日常运营',
            '店铺管理者 - 获取智能洞察和决策建议'
          ],
          coreValue: '将传统的界面操作转变为自然语言驱动的智能协作，AI Agent可直接调用系统能力完成业务操作'
        },

        // 核心架构
        architecture: {
          pattern: 'Multi-Agent + GenUI',
          description: '系统采用多Agent协作架构，每个Agent负责特定业务域，通过统一的API接口对外提供服务，返回结构化的GenUI Schema供前端动态渲染',
          layers: [
            { layer: 'AI Agent Layer', description: '5个专业Agent（店长/商品/营销/客服/财务），各自独立运行，可被外部AI调用' },
            { layer: 'Edge Function Layer', description: '每个Agent有独立的GenUI函数（{agent}-genui），处理请求并生成UI Schema' },
            { layer: 'GenUI Rendering Layer', description: '前端DynamicRenderer根据返回的ui_schema动态渲染界面组件' },
            { layer: 'Data Layer', description: 'Supabase PostgreSQL数据库，存储所有业务数据' }
          ],
          dataFlow: '外部AI发送请求 → Edge Function处理 → 查询/操作数据库 → 生成ui_schema → 前端渲染界面'
        },

        // Agent协作模式
        agentCollaboration: {
          model: '层级协作 + 领域隔离',
          hierarchy: {
            manager: { level: 1, role: '总协调者', description: '店长(小管)负责全局统筹、跨部门协调、重大决策审批' },
            domainAgents: { level: 2, role: '领域专家', description: '商品/营销/客服/财务各自负责专业领域，向店长汇报' }
          },
          collaborationPatterns: [
            { pattern: '目标分解', example: '店长设定"本月GMV增长20%"目标 → 分解任务给营销(获客预算20万)和商品(主推款选品)' },
            { pattern: '审批工作流', example: '营销创建大额活动 → 提交店长审批 → 店长批准后生效' },
            { pattern: '数据共享', example: '所有Agent共享同一数据库，财务可查看订单，客服可查看商品库存' }
          ]
        },

        // 交互范式
        interactionParadigm: {
          flow: '自然语言 → 意图识别 → 操作执行 → GenUI渲染',
          steps: [
            { step: 1, name: '输入', description: '用户或外部AI发送自然语言消息（如"查看库存不足的商品"）' },
            { step: 2, name: '理解', description: 'Agent理解意图，确定需要执行的操作类型' },
            { step: 3, name: '执行', description: '调用数据库查询或业务操作（product.query with filter）' },
            { step: 4, name: '响应', description: '生成包含ui_schema的JSON响应，包含数据表格/图表/操作按钮等' },
            { step: 5, name: '渲染', description: '前端DynamicRenderer解析ui_schema，渲染对应的React组件' }
          ],
          inputFormats: [
            { type: 'natural_language', example: '帮我看看哪些商品快没货了', description: '最常用，由Agent理解并处理' },
            { type: 'structured_command', example: '{ "intent": "product.query", "params": { "lowStock": true } }', description: '直接指定意图和参数' }
          ],
          outputFormat: {
            structure: '{ success, answer?, ui_schema?, insights?, intent, stats?, conversation_id }',
            keyField: 'ui_schema - 包含可渲染的组件数组，是GenUI的核心输出'
          }
        },

        // 业务领域概述
        businessDomains: {
          summary: '系统覆盖电商运营的五大核心领域',
          domains: [
            { 
              domain: 'product', 
              agent: '小品(商品经理)', 
              scope: '商品、分类、品牌、库存管理',
              tables: ['products', 'categories', 'brands', 'category_brands'],
              keyOperations: ['商品上下架', '库存调整', '价格修改', '选品分析']
            },
            { 
              domain: 'marketing', 
              agent: '小营(营销经理)', 
              scope: '营销活动、优惠券、促销玩法',
              tables: ['coupons', 'marketing_campaigns', 'flash_sales', 'group_buy_activities', 'payment_gifts', 'banners'],
              keyOperations: ['创建优惠券', '策划活动', '设置秒杀/拼团', '效果分析']
            },
            { 
              domain: 'service', 
              agent: '小服(客服经理)', 
              scope: '售后处理、订单跟踪、客户服务',
              tables: ['after_sales_requests', 'orders'],
              keyOperations: ['处理退换货', '更新物流', '客户投诉处理']
            },
            { 
              domain: 'finance', 
              agent: '小财(财务经理)', 
              scope: '收支管理、财务分析、会员充值',
              tables: ['orders', 'balance_transactions', 'user_balances', 'recharge_plans'],
              keyOperations: ['收入统计', '成本分析', '充值方案管理']
            },
            { 
              domain: 'manager', 
              agent: '小管(店长)', 
              scope: '全局统筹、目标管理、跨域协调',
              tables: ['goals', 'agent_settings', 'agent_roles'],
              keyOperations: ['设定目标', '审批活动', '查看全局报表', '协调资源']
            }
          ]
        },

        // 对接指南
        integrationGuide: {
          forExternalAI: {
            description: '外部AI Agent（如LangChain/Coze/Dify）可通过以下方式对接',
            steps: [
              { step: 1, action: '调用 system-info 获取系统能力概览（本接口）' },
              { step: 2, action: '调用 system-actions 获取详细操作定义' },
              { step: 3, action: '根据业务需求选择对应的 {agent}-genui 端点' },
              { step: 4, action: '发送消息，解析返回的 ui_schema 或 answer' }
            ],
            endpoints: {
              systemInfo: 'GET /functions/v1/system-info - 系统元数据和能力概览',
              systemActions: 'GET /functions/v1/system-actions - 详细操作定义',
              agentGenUI: 'POST /functions/v1/{agent}-genui - 各Agent的GenUI接口',
              adminOperations: 'POST /functions/v1/admin-operations - 直接执行操作（需认证）'
            },
            authRequired: '除 system-info 外，其他接口需要 Authorization: Bearer {JWT_TOKEN}'
          },
          bestPractices: [
            '优先使用自然语言描述需求，让Agent自动选择操作',
            '复杂查询可结合 context 提供当前视图和筛选条件',
            '批量操作建议分步执行并确认每步结果',
            '重要操作（如删除、大额活动）会触发审批流程'
          ]
        }
      },

      // ========== 系统概述（简版，保持兼容） ==========
      overview: {
        name: '智能电商管理系统',
        architecture: 'Multi-Agent + GenUI',
        features: [
          '5个专业AI Agent协作管理',
          'GenUI动态组件渲染',
          '自然语言操作界面',
          '智能审批工作流',
          '实时数据分析'
        ]
      },

      // ========== AI Agent 系统 ==========
      agents: AI_AGENTS,

      // ========== GenUI 组件库 ==========
      genUIComponents: GENUI_COMPONENTS,
      
      // ========== 系统当前状态 ==========
      statistics: {
        products: {
          total: productsCount.count || 0,
          active: productsData.data?.filter(p => p.is_active).length || 0
        },
        orders: { total: ordersCount.count || 0 },
        users: { total: usersCount.count || 0 },
        afterSales: { 
          total: afterSalesCount.count || 0,
          pending: pendingAfterSales.count || 0
        },
        coupons: { total: couponsCount.count || 0 },
        campaigns: {
          total: campaignsCount.count || 0,
          active: activeCampaigns.count || 0,
          upcoming: upcomingCampaigns.count || 0
        },
        flashSales: { total: flashSalesCount.count || 0 },
        groupBuy: { total: groupBuyCount.count || 0 },
        goals: { total: goalsCount.count || 0 }
      },

      // ========== 数据库操作定义 ==========
      operations: ADMIN_OPERATIONS,

      // ========== 数据模型 ==========
      database: {
        tables: [
          { name: 'products', description: '商品表', agent: 'product', key: ['name', 'price', 'stock_quantity', 'category', 'brand'] },
          { name: 'orders', description: '订单表', agent: 'service/finance', statusValues: ['pending', 'paid', 'shipped', 'completed', 'cancelled'] },
          { name: 'profiles', description: '用户表', roleValues: ['user', 'admin'] },
          { name: 'after_sales_requests', description: '售后表', agent: 'service', typeValues: ['return', 'exchange', 'repair'], statusValues: ['pending', 'processing', 'approved', 'rejected', 'completed'] },
          { name: 'categories', description: '分类表', agent: 'product' },
          { name: 'brands', description: '品牌表', agent: 'product' },
          { name: 'banners', description: '横幅表', agent: 'marketing' },
          { name: 'coupons', description: '优惠券表', agent: 'marketing', typeValues: ['percentage', 'fixed'], statusValues: ['active', 'inactive', 'expired'] },
          { name: 'marketing_campaigns', description: '营销活动表', agent: 'marketing', typeValues: ['promotion', 'flash_sale', 'discount', 'new_user', 'member_exclusive'], statusValues: ['draft', 'pending', 'active', 'paused', 'completed', 'rejected'] },
          { name: 'flash_sales', description: '秒杀活动表', agent: 'marketing' },
          { name: 'group_buy_activities', description: '拼团活动表', agent: 'marketing' },
          { name: 'payment_gifts', description: '支付有礼表', agent: 'marketing' },
          { name: 'goals', description: '目标表', agent: 'manager' },
          { name: 'agent_settings', description: 'Agent设置表', agent: 'manager' },
          { name: 'balance_transactions', description: '余额交易表', agent: 'finance' },
          { name: 'user_balances', description: '用户余额表', agent: 'finance' },
          { name: 'recharge_plans', description: '充值方案表', agent: 'finance' }
        ]
      },

      // ========== 示例数据 ==========
      sampleData: {
        products: productsData.data || [],
        orders: ordersData.data || [],
        categories: categoriesData.data || [],
        brands: brandsData.data || [],
        coupons: couponsData.data || [],
        campaigns: campaignsData.data || []
      },

      // ========== 业务规则 ==========
      businessRules: {
        orderWorkflow: {
          flow: 'pending -> paid -> shipped -> completed',
          rules: ['发货时必须添加物流单号', '已发货后才能标记完成', '取消订单需要说明原因']
        },
        productManagement: {
          rules: ['库存不足时应下架商品', '价格必须大于0', '商品必须关联分类']
        },
        afterSalesWorkflow: {
          flow: 'pending -> processing -> approved/rejected -> completed',
          rules: ['退款金额不能超过订单金额', '需要记录处理备注', '7天内必须处理']
        },
        campaignManagement: {
          workflow: 'draft -> pending -> active -> completed',
          rules: [
            'AI创建的活动需要经过审核才能生效',
            '活动可以被暂停和恢复',
            '活动开始时间必须早于结束时间',
            '可关联优惠券以实现自动发放'
          ],
          aiCapabilities: [
            '根据历史数据自动制定营销策略',
            '智能设置活动时间和优惠力度',
            '自动创建关联优惠券',
            '活动效果预测和复盘分析'
          ]
        },
        agentCollaboration: {
          rules: [
            'Manager可以协调其他所有Agent',
            '每个Agent专注于自己的领域',
            '跨域操作需要通过Manager协调',
            '重要操作需要人工审批'
          ]
        }
      },

      // ========== 使用说明 ==========
      usage: {
        naturalLanguageExamples: [
          { input: '查看今日销售数据', agent: 'manager', action: '统计分析' },
          { input: '库存不足的商品有哪些', agent: 'product', action: '库存查询' },
          { input: '创建一个满100减20的优惠券', agent: 'marketing', action: '创建优惠券' },
          { input: '处理待审核的售后申请', agent: 'service', action: '售后处理' },
          { input: '本月收入多少', agent: 'finance', action: '财务统计' }
        ],
        responseFormat: {
          genUI: '使用GenUI组件返回结构化界面',
          text: '自然语言回复',
          action: '执行操作并返回结果'
        }
      },
      
      // ========== 关联API ==========
      relatedApis: {
        'system-actions': {
          url: `${baseUrl}/functions/v1/system-actions`,
          description: '获取详细的可执行操作定义（页面导航、过滤、排序、Dashboard控制）',
          note: '如需了解如何控制页面UI，请调用此API'
        },
        'admin-operations': {
          url: `${baseUrl}/functions/v1/admin-operations`,
          method: 'POST',
          description: '执行管理操作（需要JWT认证）',
          requestFormat: { operation: 'string (e.g. product.query)', params: 'object' }
        },
        'marketing-genui': {
          url: `${baseUrl}/functions/v1/marketing-genui`,
          description: '营销Agent GenUI接口'
        },
        'product-genui': {
          url: `${baseUrl}/functions/v1/product-genui`,
          description: '商品Agent GenUI接口'
        },
        'service-genui': {
          url: `${baseUrl}/functions/v1/service-genui`,
          description: '客服Agent GenUI接口'
        },
        'finance-genui': {
          url: `${baseUrl}/functions/v1/finance-genui`,
          description: '财务Agent GenUI接口'
        },
        'manager-genui': {
          url: `${baseUrl}/functions/v1/manager-genui`,
          description: '店铺经理Agent GenUI接口'
        }
      },

      // ========== AI Agent 调用测试示例（供外部AI参考） ==========
      apiTestExamples: {
        description: '以下是各GenUI接口的标准调用示例，供AI Agent参考',
        
        // 通用请求格式
        commonRequestFormat: {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'apikey': '{SUPABASE_ANON_KEY}',
            'Authorization': 'Bearer {JWT_TOKEN}' // 可选，用于认证操作
          },
          bodyFormat: {
            message: 'string - 自然语言消息',
            view: 'string? - 可选，指定视图: dashboard|products|orders|...',
            context: 'object? - 可选，当前上下文信息'
          }
        },

        // 通用响应格式
        commonResponseFormat: {
          success: 'boolean - 是否成功',
          answer: 'string? - 文本回复',
          ui_schema: {
            layout: 'vertical|horizontal|grid',
            gap: 'sm|md|lg',
            components: '[UIComponent[]] - 组件数组'
          },
          insights: 'array? - 洞察列表',
          intent: 'string - 检测到的意图',
          conversation_id: 'string? - 会话ID'
        },

        // 各Agent调用示例
        examples: {
          // 店长Agent示例
          managerGenUI: {
            endpoint: `${baseUrl}/functions/v1/manager-genui`,
            scenarios: [
              {
                name: '获取仪表盘概览',
                request: { message: '查看今日数据' },
                expectedIntent: 'dashboard',
                expectedComponents: ['stats_row', 'chart']
              },
              {
                name: '查看库存预警',
                request: { message: '哪些商品库存不足' },
                expectedIntent: 'products',
                expectedComponents: ['alert', 'data_table']
              },
              {
                name: '查看订单状态',
                request: { message: '待处理订单有多少' },
                expectedIntent: 'orders',
                expectedComponents: ['stats_row', 'chart']
              },
              {
                name: '获取帮助',
                request: { message: '你能做什么' },
                expectedIntent: 'help',
                expectedComponents: ['text']
              }
            ]
          },

          // 商品Agent示例
          productGenUI: {
            endpoint: `${baseUrl}/functions/v1/product-genui`,
            scenarios: [
              {
                name: '商品统计',
                request: { message: '商品概览' },
                expectedComponents: ['stats_row']
              },
              {
                name: '低库存查询',
                request: { message: '库存不足10件的商品' },
                expectedComponents: ['data_table', 'alert']
              },
              {
                name: '分类统计',
                request: { message: '各分类商品数量' },
                expectedComponents: ['chart']
              }
            ]
          },

          // 营销Agent示例
          marketingGenUI: {
            endpoint: `${baseUrl}/functions/v1/marketing-genui`,
            scenarios: [
              {
                name: '营销概览',
                request: { message: '营销活动状态' },
                expectedComponents: ['stats_row', 'data_table']
              },
              {
                name: '优惠券查询',
                request: { message: '有效优惠券列表' },
                expectedComponents: ['data_table']
              },
              {
                name: '秒杀活动',
                request: { message: '进行中的秒杀' },
                expectedComponents: ['data_table']
              }
            ]
          },

          // 客服Agent示例
          serviceGenUI: {
            endpoint: `${baseUrl}/functions/v1/service-genui`,
            scenarios: [
              {
                name: '售后概览',
                request: { message: '待处理售后' },
                expectedComponents: ['stats_row', 'data_table']
              },
              {
                name: '退款申请',
                request: { message: '退款请求列表' },
                expectedComponents: ['data_table']
              }
            ]
          },

          // 财务Agent示例
          financeGenUI: {
            endpoint: `${baseUrl}/functions/v1/finance-genui`,
            scenarios: [
              {
                name: '财务概览',
                request: { message: '本月收入' },
                expectedComponents: ['stats_row', 'chart']
              },
              {
                name: '交易记录',
                request: { message: '最近交易' },
                expectedComponents: ['data_table']
              }
            ]
          }
        },

        // 组件类型白名单
        validComponentTypes: [
          'stats_row', 'data_table', 'chart', 'alert', 'action_buttons',
          'approval_card', 'insight_card', 'progress_bar', 'text', 'divider',
          'container', 'agent_status', 'agent_capabilities', 'agent_thinking',
          'agent_settings_card', 'agent_settings_list', 'sandbox_result',
          'insight_feed', 'approval_list'
        ],

        // 意图映射
        intentMapping: {
          manager: ['dashboard', 'products', 'orders', 'marketing', 'aftersales', 'users', 'help'],
          product: ['overview', 'stock', 'category', 'brand', 'help'],
          marketing: ['overview', 'coupons', 'campaigns', 'flashsale', 'groupbuy', 'help'],
          service: ['overview', 'aftersales', 'orders', 'help'],
          finance: ['overview', 'revenue', 'transactions', 'recharge', 'help']
        },

        // 测试验证规则
        validationRules: {
          responseStructure: [
            'success 必须为 boolean',
            'ui_schema.layout 必须为 vertical|horizontal|grid',
            'ui_schema.gap 必须为 sm|md|lg',
            'ui_schema.components 必须为数组',
            '每个component必须有 type 和 props'
          ],
          componentRules: [
            'stats_row.props.items 必须为数组',
            'chart.props.type 必须为 line|bar|pie|area',
            'chart.props.data 必须为数组',
            'data_table.props.columns 必须为数组',
            'container.props.children 可嵌套其他组件'
          ]
        }
      }
    };

    console.log('system-info v2.0.0 called');

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

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