//
//  ApiManager.swift
//  iKeyMon
//
//  Created by tracer on 13.11.25.
//

import Foundation
import Combine

@MainActor
class APIManager: ObservableObject {
    @Published var isConnected = false
    @Published var currentVersion: String = ""
    @Published var lastError: Error?
    
    private var api: AnyServerAPI?
    private let baseURL: URL
    
    init(baseURL: URL) {
        self.baseURL = baseURL
    }
    
    func connect() async {
        do {
            self.api = try await APIFactory.detectAndCreateAPI(baseURL: baseURL)
            let systemInfo = try await api!.fetchSystemInfo()
            self.currentVersion = systemInfo.version
            self.isConnected = true
            self.lastError = nil
        } catch {
            self.isConnected = false
            self.lastError = error
            self.api = nil
        }
    }
    
    func disconnect() {
        self.api = nil
        self.isConnected = false
        self.currentVersion = ""
        self.lastError = nil
    }
    
    func fetchSystemInfo() async throws -> SystemInfo {
        guard let api = api else { throw APIError.invalidResponse }
        return try await api.fetchSystemInfo()
    }
    
    func fetchLoad() async throws -> Any {
        guard let api = api else { throw APIError.invalidResponse }
        return try await api.fetchLoadData()
    }
    
    func fetchMemory() async throws -> Any {
        guard let api = api else { throw APIError.invalidResponse }
        return try await api.fetchMemoryData()
    }
    
    func fetchUtilization() async throws -> Any {
        guard let api = api else { throw APIError.invalidResponse }
        return try await api.fetchUtilizationData()
    }
}
