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

/**
 * 动态 Agent Schema API
 * 为 Coze/Dify 等外部 AI 平台提供实时系统文档和接口定义
 */

// ========== Agent 角色定义 ==========
const AGENT_ROLES = {
  marketing: {
    id: 'marketing',
    name: '营销经理',
    name_en: 'Marketing Manager',
    description: '负责营销活动、优惠券、促销策略的管理和分析',
    capabilities: ['campaign_management', 'coupon_management', 'promotion_analysis', 'user_targeting'],
    data_access: ['marketing_campaigns', 'coupons', 'flash_sales', 'group_buy_activities', 'cross_store_promotions', 'payment_gifts'],
    actions: ['create_campaign', 'approve_campaign', 'pause_campaign', 'create_coupon', 'analyze_roi']
  },
  product: {
    id: 'product',
    name: '产品经理',
    name_en: 'Product Manager',
    description: '负责商品管理、库存监控、分类品牌维护',
    capabilities: ['product_management', 'inventory_control', 'category_management', 'brand_management'],
    data_access: ['products', 'categories', 'brands', 'category_brands'],
    actions: ['update_product', 'adjust_price', 'manage_stock', 'toggle_status', 'batch_update']
  },
  finance: {
    id: 'finance',
    name: '财务经理',
    name_en: 'Finance Manager',
    description: '负责订单财务、退款处理、交易分析',
    capabilities: ['order_finance', 'refund_processing', 'transaction_analysis', 'revenue_reporting'],
    data_access: ['orders', 'order_items', 'balance_transactions', 'user_balances', 'recharge_plans'],
    actions: ['process_refund', 'approve_payment', 'generate_report', 'reconcile_accounts']
  },
  service: {
    id: 'service',
    name: '客服经理',
    name_en: 'Service Manager',
    description: '负责售后服务、客户投诉、服务质量监控',
    capabilities: ['aftersales_management', 'complaint_handling', 'service_quality', 'customer_satisfaction'],
    data_access: ['after_sales_requests', 'orders', 'products', 'profiles'],
    actions: ['approve_aftersales', 'reject_aftersales', 'assign_handler', 'escalate_issue']
  },
  manager: {
    id: 'manager',
    name: '总经理',
    name_en: 'General Manager',
    description: '全局视角，协调各部门，处理跨域决策',
    capabilities: ['cross_domain_coordination', 'strategic_planning', 'performance_monitoring', 'resource_allocation'],
    data_access: ['all'],
    actions: ['assign_task', 'set_priority', 'approve_budget', 'review_performance']
  }
};

// ========== UI 组件规范 ==========
const UI_COMPONENTS = {
  stats_row: {
    type: 'stats_row',
    description: '统计数据行，展示多个关键指标',
    props: {
      items: {
        type: 'array',
        items: {
          label: 'string - 指标名称',
          value: 'string|number - 指标值',
          change: 'number? - 变化百分比',
          trend: "'up'|'down'|'neutral'? - 趋势方向"
        }
      }
    },
    example: {
      type: 'stats_row',
      props: {
        items: [
          { label: '今日订单', value: 156, change: 12.5, trend: 'up' },
          { label: '销售额', value: '¥45,678', change: -3.2, trend: 'down' }
        ]
      }
    }
  },
  data_table: {
    type: 'data_table',
    description: '数据表格，支持分页和操作按钮',
    props: {
      columns: 'array - 列定义 [{key, label, type?}]',
      data: 'array - 表格数据',
      actions: 'array? - 行操作按钮'
    },
    example: {
      type: 'data_table',
      props: {
        columns: [
          { key: 'name', label: '商品名称' },
          { key: 'price', label: '价格', type: 'currency' },
          { key: 'stock', label: '库存', type: 'number' }
        ],
        data: [
          { name: 'iPhone 15', price: 7999, stock: 50 }
        ]
      }
    }
  },
  insight_card: {
    type: 'insight_card',
    description: '洞察卡片，展示AI分析结论',
    props: {
      title: 'string - 洞察标题',
      content: 'string - 洞察内容',
      type: "'info'|'warning'|'success'|'error' - 类型",
      actions: 'array? - 建议操作'
    }
  },
  approval_card: {
    type: 'approval_card',
    description: '审批卡片，展示待审批项',
    props: {
      id: 'string - 审批项ID',
      title: 'string - 标题',
      description: 'string - 描述',
      requestedBy: 'string - 申请人',
      createdAt: 'string - 申请时间',
      type: 'string - 审批类型',
      amount: 'number? - 金额'
    }
  },
  chart: {
    type: 'chart',
    description: '图表组件，支持多种图表类型',
    props: {
      chartType: "'line'|'bar'|'pie'|'area' - 图表类型",
      title: 'string? - 图表标题',
      data: 'array - 图表数据',
      xKey: 'string - X轴字段',
      yKey: 'string|string[] - Y轴字段'
    }
  },
  progress_bar: {
    type: 'progress_bar',
    description: '进度条，展示目标完成进度',
    props: {
      label: 'string - 标签',
      current: 'number - 当前值',
      target: 'number - 目标值',
      unit: 'string? - 单位'
    }
  },
  action_buttons: {
    type: 'action_buttons',
    description: '操作按钮组',
    props: {
      buttons: {
        type: 'array',
        items: {
          label: 'string - 按钮文字',
          action: 'string - 操作类型',
          variant: "'default'|'destructive'|'outline'? - 样式",
          params: 'object? - 操作参数'
        }
      }
    }
  },
  alert_box: {
    type: 'alert_box',
    description: '警告提示框',
    props: {
      type: "'info'|'warning'|'error'|'success' - 类型",
      title: 'string - 标题',
      message: 'string - 消息内容'
    }
  },
  text_block: {
    type: 'text_block',
    description: '文本块，支持Markdown',
    props: {
      content: 'string - 文本内容',
      format: "'plain'|'markdown'? - 格式"
    }
  }
};

// ========== Action 类型定义 ==========
const ACTION_TYPES = {
  page_action: {
    description: '页面导航和UI控制',
    actions: {
      navigate: { params: ['page'], description: '导航到指定页面' },
      filter: { params: ['field', 'value'], description: '设置过滤条件' },
      sort: { params: ['field', 'direction'], description: '设置排序' },
      select: { params: ['ids'], description: '选中指定项' },
      open_dialog: { params: ['dialog', 'data'], description: '打开对话框' },
      refresh: { params: [], description: '刷新当前视图' }
    }
  },
  data_action: {
    description: '数据操作',
    actions: {
      create: { params: ['entity', 'data'], description: '创建数据' },
      update: { params: ['entity', 'id', 'data'], description: '更新数据' },
      delete: { params: ['entity', 'id'], description: '删除数据' },
      batch_update: { params: ['entity', 'ids', 'data'], description: '批量更新' },
      query: { params: ['entity', 'filters', 'sort', 'limit'], description: '查询数据' }
    }
  },
  agent_action: {
    description: 'Agent协作动作',
    actions: {
      delegate: { params: ['target_agent', 'task', 'context'], description: '委派任务给其他Agent' },
      request_approval: { params: ['type', 'data', 'approver'], description: '请求审批' },
      notify: { params: ['target', 'message', 'priority'], description: '发送通知' },
      escalate: { params: ['issue', 'level'], description: '升级问题' }
    }
  },
  workflow_action: {
    description: '工作流控制',
    actions: {
      start_workflow: { params: ['workflow_id', 'input'], description: '启动工作流' },
      complete_step: { params: ['step_id', 'output'], description: '完成工作流步骤' },
      pause_workflow: { params: ['workflow_id'], description: '暂停工作流' },
      resume_workflow: { params: ['workflow_id'], description: '恢复工作流' }
    }
  }
};

// ========== 数据模型定义 ==========
const DATA_MODELS = {
  products: {
    table: 'products',
    description: '商品表',
    fields: {
      id: { type: 'uuid', primary: true },
      name: { type: 'text', required: true, description: '商品名称' },
      price: { type: 'numeric', required: true, description: '价格' },
      stock_quantity: { type: 'integer', default: 0, description: '库存数量' },
      category: { type: 'text', description: '分类名称' },
      brand: { type: 'text', description: '品牌名称' },
      is_active: { type: 'boolean', default: true, description: '是否上架' },
      is_hot: { type: 'boolean', default: false, description: '是否热销' },
      is_recommended: { type: 'boolean', default: false, description: '是否推荐' },
      description: { type: 'text', description: '商品描述' },
      images: { type: 'text[]', description: '图片URL列表' },
      specifications: { type: 'jsonb', description: '规格参数' }
    },
    operations: ['query', 'create', 'update', 'delete', 'batch_update']
  },
  orders: {
    table: 'orders',
    description: '订单表',
    fields: {
      id: { type: 'uuid', primary: true },
      order_number: { type: 'text', required: true, description: '订单号' },
      user_id: { type: 'uuid', required: true, description: '用户ID' },
      total_amount: { type: 'numeric', required: true, description: '订单总额' },
      status: { type: 'text', enum: ['pending', 'paid', 'shipped', 'completed', 'cancelled'], description: '订单状态' },
      shipping_address: { type: 'text', description: '收货地址' },
      tracking_number: { type: 'text', description: '物流单号' },
      notes: { type: 'text', description: '备注' }
    },
    operations: ['query', 'update', 'cancel', 'ship', 'complete']
  },
  marketing_campaigns: {
    table: 'marketing_campaigns',
    description: '营销活动表',
    fields: {
      id: { type: 'uuid', primary: true },
      name: { type: 'text', required: true, description: '活动名称' },
      type: { type: 'text', enum: ['promotion', 'flash_sale', 'discount', 'new_user', 'member_exclusive'], description: '活动类型' },
      status: { type: 'text', enum: ['draft', 'pending', 'active', 'paused', 'completed', 'rejected'], description: '状态' },
      start_date: { type: 'timestamp', required: true, description: '开始时间' },
      end_date: { type: 'timestamp', required: true, description: '结束时间' },
      description: { type: 'text', description: '活动描述' },
      config: { type: 'jsonb', description: '活动配置' },
      ai_strategy: { type: 'text', description: 'AI策略说明' },
      created_by: { type: 'text', enum: ['manual', 'ai'], description: '创建方式' }
    },
    operations: ['query', 'create', 'update', 'delete', 'approve', 'reject', 'pause', 'resume']
  },
  coupons: {
    table: 'coupons',
    description: '优惠券表',
    fields: {
      id: { type: 'uuid', primary: true },
      name: { type: 'text', required: true, description: '优惠券名称' },
      code: { type: 'text', required: true, unique: true, description: '优惠码' },
      type: { type: 'text', enum: ['percentage', 'fixed'], description: '类型' },
      discount_value: { type: 'numeric', required: true, description: '折扣值' },
      min_purchase_amount: { type: 'numeric', description: '最低消费' },
      max_discount_amount: { type: 'numeric', description: '最高抵扣' },
      total_quantity: { type: 'integer', required: true, description: '总数量' },
      used_quantity: { type: 'integer', default: 0, description: '已使用数量' },
      start_date: { type: 'timestamp', required: true },
      end_date: { type: 'timestamp', required: true },
      status: { type: 'text', enum: ['active', 'inactive', 'expired'] }
    },
    operations: ['query', 'create', 'update', 'delete', 'distribute']
  },
  after_sales_requests: {
    table: 'after_sales_requests',
    description: '售后申请表',
    fields: {
      id: { type: 'uuid', primary: true },
      order_id: { type: 'uuid', required: true, description: '关联订单' },
      product_id: { type: 'uuid', required: true, description: '关联商品' },
      user_id: { type: 'uuid', required: true, description: '用户ID' },
      type: { type: 'text', enum: ['return', 'exchange', 'repair'], description: '售后类型' },
      reason: { type: 'text', required: true, description: '原因' },
      description: { type: 'text', required: true, description: '详细描述' },
      status: { type: 'text', enum: ['pending', 'approved', 'rejected', 'processing', 'completed'], description: '状态' },
      refund_amount: { type: 'numeric', description: '退款金额' },
      admin_notes: { type: 'text', description: '处理备注' }
    },
    operations: ['query', 'approve', 'reject', 'process', 'complete']
  }
};

// ========== API 端点定义 ==========
const getApiEndpoints = (baseUrl: string) => ({
  system: {
    'agent-schema': {
      url: `${baseUrl}/functions/v1/agent-schema`,
      method: 'GET',
      description: '获取完整的Agent Schema（本接口）',
      auth: false,
      params: { format: "'full'|'compact' - 输出格式", agent: 'string? - 指定Agent角色' }
    },
    'system-info': {
      url: `${baseUrl}/functions/v1/system-info`,
      method: 'GET',
      description: '获取系统统计和状态信息',
      auth: false
    },
    'system-actions': {
      url: `${baseUrl}/functions/v1/system-actions`,
      method: 'GET',
      description: '获取可执行的系统操作定义',
      auth: false
    }
  },
  agent: {
    'marketing-genui': {
      url: `${baseUrl}/functions/v1/marketing-genui`,
      method: 'POST',
      description: '营销Agent GenUI接口',
      auth: true,
      body: { message: 'string', context: 'object?', conversation_id: 'string?' }
    },
    'product-genui': {
      url: `${baseUrl}/functions/v1/product-genui`,
      method: 'POST',
      description: '产品Agent GenUI接口',
      auth: true,
      body: { message: 'string', context: 'object?', conversation_id: 'string?' }
    },
    'finance-genui': {
      url: `${baseUrl}/functions/v1/finance-genui`,
      method: 'POST',
      description: '财务Agent GenUI接口',
      auth: true,
      body: { message: 'string', context: 'object?', conversation_id: 'string?' }
    },
    'service-genui': {
      url: `${baseUrl}/functions/v1/service-genui`,
      method: 'POST',
      description: '客服Agent GenUI接口',
      auth: true,
      body: { message: 'string', context: 'object?', conversation_id: 'string?' }
    },
    'manager-genui': {
      url: `${baseUrl}/functions/v1/manager-genui`,
      method: 'POST',
      description: '总经理Agent GenUI接口',
      auth: true,
      body: { message: 'string', context: 'object?', conversation_id: 'string?' }
    }
  },
  operations: {
    'admin-operations': {
      url: `${baseUrl}/functions/v1/admin-operations`,
      method: 'POST',
      description: '执行管理操作',
      auth: true,
      body: { operation: 'string', entity: 'string', params: 'object' }
    },
    'marketing-operations': {
      url: `${baseUrl}/functions/v1/marketing-operations`,
      method: 'POST',
      description: '执行营销操作',
      auth: true,
      body: { action: 'string', data: 'object' }
    },
    'product-operations': {
      url: `${baseUrl}/functions/v1/product-operations`,
      method: 'POST',
      description: '执行产品操作',
      auth: true,
      body: { action: 'string', data: 'object' }
    },
    'service-operations': {
      url: `${baseUrl}/functions/v1/service-operations`,
      method: 'POST',
      description: '执行售后操作',
      auth: true,
      body: { action: 'string', data: 'object' }
    }
  },
  insights: {
    'marketing-insights': {
      url: `${baseUrl}/functions/v1/marketing-insights`,
      method: 'GET',
      description: '获取营销洞察',
      auth: true
    },
    'product-insights': {
      url: `${baseUrl}/functions/v1/product-insights`,
      method: 'GET',
      description: '获取产品洞察',
      auth: true
    },
    'finance-insights': {
      url: `${baseUrl}/functions/v1/finance-insights`,
      method: 'GET',
      description: '获取财务洞察',
      auth: true
    },
    'service-insights': {
      url: `${baseUrl}/functions/v1/service-insights`,
      method: 'GET',
      description: '获取服务洞察',
      auth: true
    }
  }
});

// ========== 响应格式规范 ==========
const RESPONSE_FORMAT = {
  genui_response: {
    description: 'GenUI Agent 响应格式',
    schema: {
      message: 'string - 自然语言回复',
      ui: {
        layout: "'vertical'|'horizontal'|'grid' - 布局方式",
        components: 'UIComponent[] - UI组件列表'
      },
      actions: [{
        type: "'page_action'|'data_action'|'agent_action' - 动作类型",
        action: 'string - 具体动作',
        params: 'object - 动作参数',
        require_confirmation: 'boolean? - 是否需要确认'
      }],
      context_update: {
        selected_items: 'any[]? - 选中项',
        filters: 'object? - 过滤条件',
        view_state: 'object? - 视图状态'
      },
      metadata: {
        confidence: 'number - 置信度 0-1',
        processing_time: 'number - 处理时间ms',
        agent_id: 'string - 处理Agent'
      }
    },
    example: {
      message: '已为您找到3个待处理的售后申请',
      ui: {
        layout: 'vertical',
        components: [
          {
            type: 'stats_row',
            props: {
              items: [
                { label: '待处理', value: 3 },
                { label: '今日已处理', value: 12 }
              ]
            }
          },
          {
            type: 'data_table',
            props: {
              columns: [
                { key: 'order_number', label: '订单号' },
                { key: 'type', label: '类型' },
                { key: 'status', label: '状态' }
              ],
              data: []
            }
          }
        ]
      },
      actions: [
        {
          type: 'page_action',
          action: 'filter',
          params: { field: 'status', value: 'pending' }
        }
      ]
    }
  }
};

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';
    const agentFilter = url.searchParams.get('agent');
    
    const supabase = createClient(
      Deno.env.get('SUPABASE_URL') ?? '',
      Deno.env.get('SUPABASE_ANON_KEY') ?? ''
    );

    const baseUrl = Deno.env.get('SUPABASE_URL');

    // 获取实时统计数据
    const [productsCount, ordersCount, campaignsCount, afterSalesCount] = await Promise.all([
      supabase.from('products').select('*', { count: 'exact', head: true }),
      supabase.from('orders').select('*', { count: 'exact', head: true }),
      supabase.from('marketing_campaigns').select('*', { count: 'exact', head: true }),
      supabase.from('after_sales_requests').select('*', { count: 'exact', head: true })
    ]);

    // 获取待处理项统计
    const [pendingOrders, pendingAfterSales, pendingCampaigns] = await Promise.all([
      supabase.from('orders').select('*', { count: 'exact', head: true }).eq('status', 'pending'),
      supabase.from('after_sales_requests').select('*', { count: 'exact', head: true }).eq('status', 'pending'),
      supabase.from('marketing_campaigns').select('*', { count: 'exact', head: true }).eq('status', 'pending')
    ]);

    const schema: any = {
      version: '2.0.0',
      generated_at: new Date().toISOString(),
      description: '智能电商管理系统 - Agent 动态 Schema',
      
      // 实时系统状态
      system_status: {
        total: {
          products: productsCount.count || 0,
          orders: ordersCount.count || 0,
          campaigns: campaignsCount.count || 0,
          after_sales: afterSalesCount.count || 0
        },
        pending: {
          orders: pendingOrders.count || 0,
          after_sales: pendingAfterSales.count || 0,
          campaigns: pendingCampaigns.count || 0
        }
      },

      // Agent 定义
      agents: agentFilter ? { [agentFilter]: AGENT_ROLES[agentFilter as keyof typeof AGENT_ROLES] } : AGENT_ROLES,
      
      // API 端点
      api_endpoints: getApiEndpoints(baseUrl || ''),
      
      // 数据模型
      data_models: DATA_MODELS,
      
      // UI 组件
      ui_components: UI_COMPONENTS,
      
      // Action 类型
      action_types: ACTION_TYPES,
      
      // 响应格式
      response_format: RESPONSE_FORMAT,

      // 集成说明
      integration_guide: {
        coze: {
          description: 'Coze 集成指南',
          steps: [
            '1. 在 Coze 工作流中调用 agent-schema API 获取最新 Schema',
            '2. 根据用户意图选择对应的 Agent 角色',
            '3. 调用对应的 genui 接口获取响应',
            '4. 解析 ui.components 渲染界面',
            '5. 执行 actions 中的操作'
          ],
          webhook_format: {
            input: { message: 'string', user_id: 'string', context: 'object?' },
            output: 'GenUI Response Format'
          }
        },
        dify: {
          description: 'Dify 集成指南',
          steps: [
            '1. 在 Dify 工作流开始时调用 agent-schema API',
            '2. 将 Schema 作为系统上下文传递给 LLM',
            '3. 使用 HTTP 节点调用对应的操作接口',
            '4. 返回标准 GenUI 响应格式'
          ],
          tool_definition: {
            name: 'execute_action',
            description: '执行系统操作',
            parameters: {
              type: 'object',
              properties: {
                action_type: { type: 'string', enum: ['page_action', 'data_action', 'agent_action'] },
                action: { type: 'string' },
                params: { type: 'object' }
              }
            }
          }
        }
      }
    };

    // Compact 格式只返回关键信息
    if (format === 'compact') {
      delete schema.integration_guide;
      delete schema.response_format;
      schema.ui_components = Object.keys(UI_COMPONENTS);
      schema.action_types = Object.keys(ACTION_TYPES);
    }

    console.log(`agent-schema called, format: ${format}, agent: ${agentFilter || 'all'}`);

    return new Response(
      JSON.stringify(schema, 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' 
        } 
      }
    );
  }
});
