import SwiftUI
import TokenLensCore

@MainActor
final class UsageStore: ObservableObject {
    static let shared = UsageStore()

    @Published var summary = UsageSummary.make(records: [])
    @Published var isRefreshing = false
    @Published var refreshCount = 0

    private let scanner = TokenUsageScanner()
    private var refreshTask: Task<Void, Never>?

    private init() {}

    func start() {
        guard refreshTask == nil else { return }
        refreshTask = Task { [weak self] in
            guard let self else { return }
            await self.refresh()
            while !Task.isCancelled {
                try? await Task.sleep(for: .seconds(15))
                await self.refresh(silent: true)
            }
        }
    }

    func refresh(silent: Bool = false) async {
        if isRefreshing { return }
        if !silent { isRefreshing = true }
        let next = await scanner.scan()
        if silent {
            summary = next
            refreshCount += 1
            isRefreshing = false
        } else {
            withAnimation(.smooth(duration: 0.45)) {
                summary = next
                refreshCount += 1
                isRefreshing = false
            }
        }
    }
}
