import { Body, Controller, Post, Get, Path, Query, Route, Tags } from 'tsoa';
import { RecommendationService } from '../../core/ai/RecommendationService';

interface RecordBehaviorRequest {
  tenantId: string;
  userId: string;
  itemId: string;
  behaviorType: 'view' | 'click' | 'purchase' | 'favorite';
  weight?: number;
  context?: any;
}

interface RecordBehaviorResponse {
  status: string;
  message: string;
}

interface UpdateItemRequest {
  tenantId: string;
  itemId: string;
  category?: string;
  price?: number;
  tags?: string[];
  popularity?: number;
}

interface UpdateItemResponse {
  status: string;
  message: string;
}

interface GetRecommendationsRequest {
  tenantId: string;
  userId: string;
  count?: number;
  algorithms?: string[];
  context?: any;
}

interface GetRecommendationsResponse {
  recommendations: string[];
  algorithm: string;
  score: number;
  fromCache: boolean;
  processingTime: number;
  status: string;
}

interface RecommendationStatsResponse {
  totalRecommendations: number;
  avgScore: string;
  maxScore: string;
  minScore: string;
  uniqueUsers: number;
}

interface CleanupCacheResponse {
  status: string;
  message: string;
  cleanedCount?: number;
}

/**
 * [AI_REC_01] 推荐系统API控制器
 */
@Route('recommendation')
@Tags('Recommendation')
export class RecommendationController extends Controller {
  /**
   * 记录用户行为
   */
  @Post('record-behavior')
  async recordUserBehavior(@Body() request: RecordBehaviorRequest): Promise<RecordBehaviorResponse> {
    try {
      await RecommendationService.recordUserBehavior({
        tenantId: request.tenantId,
        userId: request.userId,
        itemId: request.itemId,
        behaviorType: request.behaviorType,
        weight: request.weight,
        context: request.context
      });

      return {
        status: 'success',
        message: 'User behavior recorded successfully'
      };
    } catch (error) {
      this.setStatus(500);
      return {
        status: 'error',
        message: `Failed to record user behavior: ${error.message}`
      };
    }
  }

  /**
   * 更新商品属性
   */
  @Post('update-item')
  async updateItemAttributes(@Body() request: UpdateItemRequest): Promise<UpdateItemResponse> {
    try {
      await RecommendationService.updateItemAttributes({
        tenantId: request.tenantId,
        itemId: request.itemId,
        category: request.category,
        price: request.price,
        tags: request.tags,
        popularity: request.popularity
      });

      return {
        status: 'success',
        message: 'Item attributes updated successfully'
      };
    } catch (error) {
      this.setStatus(500);
      return {
        status: 'error',
        message: `Failed to update item attributes: ${error.message}`
      };
    }
  }

  /**
   * 获取推荐结果
   */
  @Post('recommendations')
  async getRecommendations(@Body() request: GetRecommendationsRequest): Promise<GetRecommendationsResponse> {
    const startTime = Date.now();
    
    try {
      const result = await RecommendationService.getRecommendations({
        tenantId: request.tenantId,
        userId: request.userId,
        count: request.count,
        algorithms: request.algorithms,
        context: request.context
      });

      const processingTime = Date.now() - startTime;

      return {
        recommendations: result.recommendations,
        algorithm: result.algorithm,
        score: result.score,
        fromCache: result.fromCache,
        processingTime,
        status: 'success'
      };
    } catch (error) {
      this.setStatus(500);
      const processingTime = Date.now() - startTime;
      
      return {
        recommendations: [],
        algorithm: 'error',
        score: 0,
        fromCache: false,
        processingTime,
        status: `error: ${error.message}`
      };
    }
  }

  /**
   * 获取推荐效果统计
   */
  @Get('stats')
  async getRecommendationStats(@Query() tenantId: string): Promise<RecommendationStatsResponse> {
    try {
      const stats = await RecommendationService.getRecommendationStats(tenantId);
      
      return {
        totalRecommendations: stats.totalRecommendations,
        avgScore: stats.avgScore,
        maxScore: stats.maxScore,
        minScore: stats.minScore,
        uniqueUsers: stats.uniqueUsers
      };
    } catch (error) {
      this.setStatus(500);
      return {
        totalRecommendations: 0,
        avgScore: '0',
        maxScore: '0',
        minScore: '0',
        uniqueUsers: 0
      };
    }
  }

  /**
   * 清理过期缓存
   */
  @Post('cleanup-cache')
  async cleanupExpiredCache(@Body() request: { tenantId: string }): Promise<CleanupCacheResponse> {
    try {
      await RecommendationService.cleanupExpiredCache(request.tenantId);
      
      return {
        status: 'success',
        message: 'Expired cache cleaned successfully'
      };
    } catch (error) {
      this.setStatus(500);
      return {
        status: 'error',
        message: `Failed to cleanup cache: ${error.message}`
      };
    }
  }

  /**
   * 初始化推荐服务
   */
  @Post('init')
  async initRecommendation(): Promise<{ status: string; message: string }> {
    try {
      await RecommendationService.initTable();
      return { status: 'success', message: 'Recommendation service initialized' };
    } catch (error) {
      this.setStatus(500);
      return { status: 'error', message: error.message };
    }
  }

  /**
   * 健康检查
   */
  @Get('health')
  async healthCheck(): Promise<{ status: string; service: string; timestamp: Date }> {
    return {
      status: 'healthy',
      service: 'RecommendationService',
      timestamp: new Date()
    };
  }

  /**
   * 测试推荐算法
   */
  @Post('test-algorithm')
  async testAlgorithm(@Body() request: {
    tenantId: string;
    userId: string;
    algorithm: string;
    testData?: any;
  }): Promise<{
    status: string;
    algorithm: string;
    recommendations: string[];
    score: number;
    processingTime: number;
  }> {
    const startTime = Date.now();
    
    try {
      // 模拟测试算法性能
      const mockRecommendations = await this.generateMockRecommendations(request.algorithm);
      const processingTime = Date.now() - startTime;

      return {
        status: 'success',
        algorithm: request.algorithm,
        recommendations: mockRecommendations,
        score: parseFloat((Math.random() * 0.3 + 0.7).toFixed(2)),
        processingTime
      };
    } catch (error) {
      this.setStatus(500);
      return {
        status: 'error',
        algorithm: request.algorithm,
        recommendations: [],
        score: 0,
        processingTime: Date.now() - startTime
      };
    }
  }

  /**
   * 生成模拟推荐结果
   */
  private async generateMockRecommendations(algorithm: string): Promise<string[]> {
    const mockItems = [
      'item_001', 'item_002', 'item_003', 'item_004', 'item_005',
      'item_006', 'item_007', 'item_008', 'item_009', 'item_010'
    ];

    // 基于算法类型生成不同的推荐结果
    switch (algorithm) {
      case 'content_based':
        return mockItems.slice(0, 5);
      case 'collaborative_filtering':
        return mockItems.slice(2, 7);
      case 'hybrid':
        return mockItems.slice(1, 6);
      default:
        return mockItems.slice(0, 3);
    }
  }

  /**
   * 获取算法配置
   */
  @Get('algorithm-config')
  async getAlgorithmConfig(@Query() tenantId: string): Promise<{
    algorithms: Array<{
      name: string;
      enabled: boolean;
      weight: number;
      parameters: any;
    }>;
  }> {
    try {
      // 模拟算法配置
      const algorithms = [
        {
          name: 'content_based',
          enabled: true,
          weight: 0.4,
          parameters: { similarityThreshold: 0.7 }
        },
        {
          name: 'collaborative_filtering',
          enabled: true,
          weight: 0.6,
          parameters: { kNeighbors: 10 }
        },
        {
          name: 'hybrid',
          enabled: true,
          weight: 1.0,
          parameters: { fusionMethod: 'weighted' }
        }
      ];

      return { algorithms };
    } catch (error) {
      this.setStatus(500);
      return { algorithms: [] };
    }
  }
}