//
//  LoadingTextGenerator.swift
//  SportsTime
//
//  Generates unique loading messages using Apple Foundation Models.
//  Falls back to predefined messages on unsupported devices.
//

import Foundation
#if canImport(FoundationModels)
import FoundationModels
#endif

actor LoadingTextGenerator {

    static let shared = LoadingTextGenerator()

    private static let fallbackMessages = [
        "Hang tight, we're finding the best routes...",
        "Scanning stadiums across the country...",
        "Building your dream road trip...",
        "Calculating the perfect game day schedule...",
        "Finding the best matchups for you...",
        "Mapping out your adventure...",
        "Checking stadium schedules...",
        "Putting together some epic trips...",
        "Hold on, great trips incoming...",
        "Crunching the numbers on routes...",
        "Almost there, planning magic happening...",
        "Finding games you'll love..."
    ]

    private var usedMessages: Set<String> = []

    /// Generates a unique loading message.
    /// Uses Foundation Models if available, falls back to predefined messages.
    func generateMessage() async -> String {
        #if canImport(FoundationModels)
        // Try Foundation Models first
        if let message = await generateWithFoundationModels() {
            return message
        }
        #endif

        // Fall back to predefined messages
        return getNextFallbackMessage()
    }

    #if canImport(FoundationModels)
    private func generateWithFoundationModels() async -> String? {
        // Check availability
        guard case .available = SystemLanguageModel.default.availability else {
            return nil
        }

        do {
            let session = LanguageModelSession(instructions: """
                Generate a short, friendly loading message for a sports road trip planning app.
                The message should be casual, fun, and 8-12 words.
                Don't use emojis. Don't start with "We're" or "We are".
                Examples: "Hang tight, finding the best routes for you...",
                "Calculating the perfect game day adventure...",
                "Almost there, great trips are brewing..."
                """
            )

            let response = try await session.respond(to: "Generate one loading message")
            let message = response.content.trimmingCharacters(in: .whitespacesAndNewlines)

            // Validate message isn't empty and is reasonable length
            guard message.count >= 10 && message.count <= 80 else {
                return nil
            }

            return message
        } catch {
            return nil
        }
    }
    #endif

    private func getNextFallbackMessage() -> String {
        // Reset if we've used all messages
        if usedMessages.count >= Self.fallbackMessages.count {
            usedMessages.removeAll()
        }

        // Pick a random unused message
        let availableMessages = Self.fallbackMessages.filter { !usedMessages.contains($0) }
        let message = availableMessages.randomElement() ?? Self.fallbackMessages[0]
        usedMessages.insert(message)
        return message
    }

    /// Reset used messages (for testing or new session)
    func reset() {
        usedMessages.removeAll()
    }
}
