//
//  OneSongSessionManagerB.swift
//  vibes
//
//  Manages persistent state for One Song chat sessions
//

import SwiftUI

class OneSongSessionManagerB: ObservableObject {
    static let shared = OneSongSessionManagerB()

    @Published var iterations: [SongIteration] = []
    @Published var currentIndex: Int = 0
    @Published var suggestionChips: [String] = []

    private var usedSongNames: Set<String> = []
    private let availableSongs = (1...9).map { "song\($0)" }

    private init() {}

    // Add a new iteration
    func addIteration(_ iteration: SongIteration) {
        iterations.append(iteration)
        currentIndex = iterations.count - 1
        usedSongNames.insert(iteration.audioAssetName)
    }

    // Update current index
    func setCurrentIndex(_ index: Int) {
        guard index >= 0 && index < iterations.count else { return }
        currentIndex = index
    }

    // Update suggestion chips
    func updateSuggestionChips(_ chips: [String]) {
        suggestionChips = chips
    }

    // Get a unique song name that hasn't been used yet
    func getUnusedSongName() -> String {
        // Get songs that haven't been used yet
        let unusedSongs = availableSongs.filter { !usedSongNames.contains($0) }

        // If we have unused songs, pick one randomly
        if !unusedSongs.isEmpty {
            return unusedSongs.randomElement() ?? availableSongs.randomElement()!
        }

        // If all songs have been used, allow duplicates
        return availableSongs.randomElement()!
    }

    // Reset session (clear all state)
    func resetSession() {
        iterations = []
        currentIndex = 0
        suggestionChips = []
        usedSongNames.removeAll()
    }

    // Check if session has content
    var hasContent: Bool {
        return !iterations.isEmpty
    }
}
