import Foundation
import Observation
import VelodyDomain
import VelodyNetworking
import VelodyPersistence
import VelodySync
import VelodyUtilities

@MainActor
@Observable
final class MacLibraryViewModel {
    var tracks: [LibraryTrack] = []
    var selectedFolderPath = "No folder selected"
    var syncStatus = "Sync not started"

    private let folderAccessService = FolderAccessService()
    private let keychainService = MemoryKeychainService()
    private let store = InMemoryLocalLibraryStore()
    private let syncCoordinator: PlaceholderSyncCoordinator
    private var hasLoaded = false

    init() {
        let environment = ServerEnvironment(
            baseURL: URL(string: "http://localhost:3000")!,
            appVersion: "0.1.0"
        )
        let apiClient = StubVelodyAPIClient(environment: environment)
        self.syncCoordinator = PlaceholderSyncCoordinator(
            apiClient: apiClient,
            store: store
        )
        if let url = folderAccessService.storedFolderURL() {
            selectedFolderPath = url.path
        }
    }

    func loadIfNeeded() async {
        guard !hasLoaded else { return }
        hasLoaded = true
        await refreshSyncStatus()
        await keychainService.save("placeholder-bootstrap-token", forKey: "bootstrap-token")
    }

    func refreshSyncStatus() async {
        do {
            let result = try await syncCoordinator.performInitialSync()
            tracks = result.tracks
            syncStatus = result.statusMessage
        } catch {
            syncStatus = "Sync placeholder failed: \(error.localizedDescription)"
        }
    }

    func chooseFolder() {
        if let url = folderAccessService.chooseFolder() {
            selectedFolderPath = url.path
        }
    }
}
