//
//  DemoDataGenerator.swift
//  LotteryTracker
//
//  Created by aaa on 2026/1/22.
//

import Foundation
internal import CoreData

class DemoDataGenerator {
    private let context: NSManagedObjectContext
    
    init(context: NSManagedObjectContext) {
        self.context = context
    }
    
    // 生成演示数据
    func generateDemoData(count: Int = 50) {
        clearAllData()
        
        let types: [LotteryType] = [.doubleColorBall, .superLotto, .happy8, .sevenStar]
        let calendar = Calendar.current
        let now = Date()
        
        for i in 1...count {
            let ticket = LotteryTicket(context: context)
            ticket.id = UUID()
            
            // 随机选择类型
            let type = types.randomElement() ?? .doubleColorBall
            ticket.lotteryType = type
            
            // 生成号码
            ticket.numbers = generateNumbers(for: type)
            
            // 随机注数（1-10）
            ticket.betCount = Int16.random(in: 1...10)
            
            // 随机金额（每注2-20元）
            let amountPerBet: Int16 = 2
            ticket.amount = Float(ticket.betCount * amountPerBet)
            
            // 随机购买日期（过去60天内）
            let daysAgo = Int.random(in: 0...60)
            let purchaseDate = calendar.date(byAdding: .day, value: -daysAgo, to: now)!
            ticket.date = purchaseDate
            
            // 随机开奖日期（购买后1-30天）
            let drawDays = Int.random(in: 1...30)
            let drawDate = calendar.date(byAdding: .day, value: drawDays, to: purchaseDate)!
            ticket.drawDate = drawDate
            
            // 随机状态（30%中奖，30%未中，40%待开奖）
            let status = Int.random(in: 0...100)
            if status < 30 {
                ticket.ticketStatus = .won
                ticket.prizeAmount = ticket.amount * Float.random(in: 1...50)
            } else if status < 60 {
                ticket.ticketStatus = .lost
                ticket.prizeAmount = 0
            } else {
                ticket.ticketStatus = .pending
                ticket.prizeAmount = 0
            }
            
            print("🎫 生成记录 \(i)/\(count): \(type.rawValue), " + Formatters.formatCurrency(ticket.amount))
        }
        
        do {
            try context.save()
            print("✅ 成功生成 \(count) 条演示数据")
            
            // 发送数据更新通知
            NotificationCenter.default.post(name: .ticketsUpdated, object: nil)
        } catch {
            print("❌ 保存演示数据失败: \(error)")
        }
    }
    
    // 生成号码
    private func generateNumbers(for type: LotteryType) -> String {
        switch type {
        case .doubleColorBall:
            let redBalls = (1...33).shuffled().prefix(6).map { String(format: "%02d", $0) }
            let blueBall = String(format: "%02d", Int.random(in: 1...16))
            return "\(redBalls.joined(separator: " ")) + \(blueBall)"
            
        case .superLotto:
            let frontBalls = (1...35).shuffled().prefix(5).map { String(format: "%02d", $0) }
            let backBalls = (1...12).shuffled().prefix(2).map { String(format: "%02d", $0) }
            return "\(frontBalls.joined(separator: " ")) + \(backBalls.joined(separator: " "))"
            
        case .happy8:
            let numbers = (0...9).shuffled().prefix(3).map { String($0) }
            return numbers.joined(separator: " ")
            
        case .sevenStar:
            let numbers = (0...9).shuffled().prefix(7).map { String($0) }
            return numbers.joined(separator: " ")
            
        case .other:
            return "随机号码"
        }
    }
    
    // 清空所有数据
    private func clearAllData() {
        let fetchRequest: NSFetchRequest<NSFetchRequestResult> = LotteryTicket.fetchRequest()
        let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
        
        do {
            try context.execute(deleteRequest)
            print("✅ 清空现有数据")
        } catch {
            print("❌ 清空数据失败: \(error)")
        }
    }
}
