import Foundation

public enum JetBrainsProviderDescriptor {
    public static let descriptor: ProviderDescriptor = Self.makeDescriptor()

    static func makeDescriptor() -> ProviderDescriptor {
        ProviderDescriptor(
            id: .jetbrains,
            settingsSection: .init(JetBrainsProviderSettingsKey.self, credentialSettings: { _ in
                JetBrainsProviderSettings(ideBasePath: nil)
            }),
            metadata: ProviderMetadata(
                id: .jetbrains,
                displayName: "JetBrains AI",
                shortDisplayName: "JetBrains",
                sessionLabel: "Current",
                weeklyLabel: "Refill",
                opusLabel: nil,
                supportsOpus: false,
                supportsCredits: false,
                creditsHint: "",
                toggleTitle: "Show JetBrains AI usage",
                cliName: "jetbrains",
                defaultEnabled: false,
                widgetSelectable: false,
                isPrimaryProvider: false,
                usesAccountFallback: false,
                debugLogUnavailableMessage: "JetBrains AI debug log not yet implemented",
                dashboardURL: nil,
                statusPageURL: nil),
            branding: ProviderBranding(
                iconStyle: .init(provider: .jetbrains),
                iconResourceName: "ProviderIcon-jetbrains",
                color: ProviderColor(red: 255 / 255, green: 51 / 255, blue: 153 / 255),
                confettiPalette: [
                    ProviderColor(hex: 0x6B57FF),
                    ProviderColor(hex: 0x21D789),
                    ProviderColor(hex: 0x000000),
                ]),
            tokenCost: ProviderTokenCostConfig(
                supportsTokenCost: false,
                noDataMessage: { "JetBrains AI cost summary is not supported." }),
            fetchPlan: ProviderFetchPlan(
                sourceModes: [.auto, .cli],
                pipeline: ProviderFetchPipeline(resolveStrategies: { _ in [JetBrainsStatusFetchStrategy()] })),
            cli: ProviderCLIConfig(
                name: "jetbrains",
                versionDetector: nil))
    }
}

struct JetBrainsStatusFetchStrategy: ProviderFetchStrategy {
    let id: String = "jetbrains.local"
    let kind: ProviderFetchKind = .localProbe

    func isAvailable(_: ProviderFetchContext) async -> Bool {
        true
    }

    func fetch(_ context: ProviderFetchContext) async throws -> ProviderFetchResult {
        let probe = JetBrainsStatusProbe(settings: context.settings)
        let snap = try await probe.fetch()
        let usage = try snap.toUsageSnapshot()
        return self.makeResult(
            usage: usage,
            sourceLabel: "local")
    }

    func shouldFallback(on _: Error, context _: ProviderFetchContext) -> Bool {
        false
    }
}
