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 DASHBOARD_WIDGETS = {
  agent_status: { id: 'agent_status', nameCN: 'Agent状态栏', type: 'status', description: '显示小管状态、今日洞察、待审批、已完成数量' },
  store_goal: { id: 'store_goal', nameCN: '经营目标卡片', type: 'goal', description: '显示本月经营目标和完成进度' },
  quick_actions: { id: 'quick_actions', nameCN: '快捷操作', type: 'actions', description: '商品管理、用户管理、订单处理、营销活动快捷入口' },
  pending_approvals: { id: 'pending_approvals', nameCN: '待审批列表', type: 'list', description: '显示等待审批的营销活动、商品、退款申请' },
  sales_trend: { id: 'sales_trend', nameCN: '销售趋势图', type: 'chart', description: '7日销售金额和订单数趋势' },
  order_status: { id: 'order_status', nameCN: '订单状态分布', type: 'chart', description: '各状态订单数量饼图' },
  category_stats: { id: 'category_stats', nameCN: '类目统计', type: 'chart', description: '各类目商品数量柱状图' },
  user_growth: { id: 'user_growth', nameCN: '用户增长', type: 'chart', description: '近6个月用户增长面积图' },
  insight_feed: { id: 'insight_feed', nameCN: 'AI洞察流', type: 'feed', description: 'AI生成的经营洞察和建议' },
  stats_cards: { id: 'stats_cards', nameCN: '统计卡片', type: 'stats', description: '总商品、总用户、总订单、总收入概览' }
};

// 预设布局
const PRESET_LAYOUTS = {
  default: { name: '默认布局', widgets: ['agent_status', 'store_goal', 'quick_actions', 'pending_approvals', 'stats_cards', 'sales_trend', 'order_status', 'category_stats', 'user_growth', 'insight_feed'] },
  compact: { name: '紧凑布局', widgets: ['agent_status', 'stats_cards', 'pending_approvals', 'insight_feed'] },
  analytics: { name: '数据分析', widgets: ['stats_cards', 'sales_trend', 'order_status', 'category_stats', 'user_growth'] },
  approvals: { name: '审批视图', widgets: ['agent_status', 'store_goal', 'pending_approvals', 'insight_feed'] }
};

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

  try {
    // 尝试从数据库读取能力定义
    const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
    const supabaseKey = Deno.env.get('SUPABASE_ANON_KEY')!;
    const supabase = createClient(supabaseUrl, supabaseKey);

    const { data: capabilities, error } = await supabase
      .from('system_capabilities')
      .select('*')
      .eq('is_active', true)
      .order('category')
      .order('display_order');

    // 基础定义（数据库扩展或默认）
    const pageActions: Record<string, unknown> = {};
    const dataActions: Record<string, unknown> = {};
    const dashboardActions: Record<string, unknown> = {};
    const metadata: Record<string, unknown> = {};

    // 如果数据库有数据，合并数据库的定义
    if (!error && capabilities && capabilities.length > 0) {
      console.log(`Loaded ${capabilities.length} capabilities from database`);
      
      capabilities.forEach((cap: any) => {
        if (cap.category === 'page_action') {
          pageActions[cap.type] = {
            type: cap.type,
            name: cap.name,
            description: cap.description,
            params: cap.params,
            examples: cap.examples
          };
        } else if (cap.category === 'data_action') {
          dataActions[cap.type] = {
            type: cap.type,
            name: cap.name,
            description: cap.description,
            params: cap.params,
            examples: cap.examples,
            ...(cap.metadata || {})
          };
        } else if (cap.category === 'dashboard_action') {
          dashboardActions[cap.type] = {
            type: cap.type,
            name: cap.name,
            description: cap.description,
            params: cap.params,
            examples: cap.examples
          };
        } else if (cap.category === 'metadata') {
          metadata[cap.type] = {
            name: cap.name,
            description: cap.description,
            data: cap.metadata,
            examples: cap.examples
          };
        }
      });
    }

    // 默认页面动作（如果数据库没有）
    if (Object.keys(pageActions).length === 0) {
      Object.assign(pageActions, {
        navigate: { 
          type: 'navigate',
          description: '导航到指定页面', 
          params: {
            tab: { type: 'string', required: true, enum: ['home', 'overview', 'products', 'orders', 'users', 'categories', 'brands', 'banners', 'coupons', 'aftersales', 'marketing'] }
          },
          examples: [{ input: '打开商品管理', output: { type: 'navigate', params: { tab: 'products' } } }]
        },
        filter: { 
          type: 'filter',
          description: '过滤页面数据', 
          params: {
            tab: { type: 'string', required: true },
            filters: { type: 'object', required: true }
          },
          examples: [{ input: '显示待发货订单', output: { type: 'filter', params: { tab: 'orders', filters: { status: 'pending' } } } }]
        },
        sort: { 
          type: 'sort',
          description: '排序页面数据', 
          params: {
            tab: { type: 'string', required: true },
            field: { type: 'string', required: true },
            direction: { type: 'string', required: true, enum: ['asc', 'desc'] }
          }
        },
        search: { 
          type: 'search',
          description: '搜索页面数据', 
          params: {
            tab: { type: 'string', required: true },
            keyword: { type: 'string', required: true }
          }
        },
        set_page_state: { 
          type: 'set_page_state',
          description: '综合设置页面状态', 
          params: {
            tab: { type: 'string', required: true },
            filters: { type: 'object', required: false },
            sort: { type: 'object', required: false },
            search: { type: 'string', required: false }
          }
        }
      });
    }

    // 默认数据动作（如果数据库没有）
    if (Object.keys(dataActions).length === 0) {
      Object.assign(dataActions, {
        create_product: { type: 'create_product', description: '创建新商品' },
        create_category: { type: 'create_category', description: '创建新分类' },
        create_brand: { type: 'create_brand', description: '创建新品牌' },
        create_banner: { type: 'create_banner', description: '创建新横幅' },
        create_coupon: { type: 'create_coupon', description: '创建优惠券' },
        update_order: { type: 'update_order', description: '更新订单' },
        update_product: { type: 'update_product', description: '更新商品' }
      });
    }

    // 仪表板动作（始终包含）
    const dashboardActionsDefinition = {
      configure_widgets: {
        type: 'configure_widgets',
        description: '配置仪表板组件的显示/隐藏',
        params: {
          show: { type: 'array', required: false, description: '要显示的组件ID列表' },
          hide: { type: 'array', required: false, description: '要隐藏的组件ID列表' }
        },
        examples: [
          { input: '只显示销售数据', output: { kind: 'dashboard_action', type: 'configure_widgets', params: { show: ['sales_trend', 'stats_cards'] } } },
          { input: '隐藏图表', output: { kind: 'dashboard_action', type: 'configure_widgets', params: { hide: ['sales_trend', 'order_status', 'category_stats', 'user_growth'] } } }
        ]
      },
      focus_widget: {
        type: 'focus_widget',
        description: '聚焦到单个组件',
        params: {
          widget: { type: 'string', required: true, description: '要聚焦的组件ID' }
        },
        examples: [
          { input: '看一下待审批', output: { kind: 'dashboard_action', type: 'focus_widget', params: { widget: 'pending_approvals' } } }
        ]
      },
      set_layout: {
        type: 'set_layout',
        description: '切换仪表板布局模式',
        params: {
          layout: { type: 'string', required: true, enum: ['default', 'compact', 'analytics', 'approvals'], description: '布局模式' }
        },
        examples: [
          { input: '切换到数据分析视图', output: { kind: 'dashboard_action', type: 'set_layout', params: { layout: 'analytics' } } },
          { input: '显示紧凑视图', output: { kind: 'dashboard_action', type: 'set_layout', params: { layout: 'compact' } } }
        ]
      },
      refresh_widget: {
        type: 'refresh_widget',
        description: '刷新指定组件的数据',
        params: {
          widgets: { type: 'array', required: true, description: '要刷新的组件ID列表' }
        },
        examples: [
          { input: '刷新洞察数据', output: { kind: 'dashboard_action', type: 'refresh_widget', params: { widgets: ['insight_feed'] } } }
        ]
      },
      set_time_range: {
        type: 'set_time_range',
        description: '设置数据时间范围',
        params: {
          timeRange: { type: 'string', required: true, enum: ['today', 'week', 'month', 'quarter', 'year'], description: '时间范围' }
        },
        examples: [
          { input: '显示本月数据', output: { kind: 'dashboard_action', type: 'set_time_range', params: { timeRange: 'month' } } }
        ]
      }
    };

    const result = {
      version: '2.0.0',
      description: '系统可执行操作定义 - 包含页面控制和仪表板组件控制',
      source: capabilities && capabilities.length > 0 ? 'database+default' : 'default',
      lastUpdated: new Date().toISOString(),
      
      pageActions,
      dataActions,
      dashboardActions: { ...dashboardActionsDefinition, ...dashboardActions },
      
      // 仪表板元数据
      dashboardMetadata: {
        widgets: DASHBOARD_WIDGETS,
        layouts: PRESET_LAYOUTS,
        validWidgetIds: Object.keys(DASHBOARD_WIDGETS),
        validLayoutIds: Object.keys(PRESET_LAYOUTS)
      },
      
      metadata: {
        validTabs: ['home', 'overview', 'products', 'orders', 'users', 'categories', 'brands', 'banners', 'coupons', 'aftersales', 'marketing'],
        ...metadata
      },
      
      responseFormat: {
        description: '在回复中使用标记块返回操作',
        pageActionFormat: {
          description: '页面控制动作使用 [PAGE_ACTION] 标记',
          example: '[PAGE_ACTION]\n{"kind":"page_action","type":"navigate","params":{"tab":"orders"}}\n[/PAGE_ACTION]'
        },
        dashboardActionFormat: {
          description: '仪表板控制动作使用 [DASHBOARD_ACTION] 标记',
          example: '[DASHBOARD_ACTION]\n{"kind":"dashboard_action","type":"set_layout","params":{"layout":"analytics"}}\n[/DASHBOARD_ACTION]'
        }
      }
    };

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