import Foundation
import Testing

@testable import NucleicCore

/// Locks the parse of Anthropic's `/api/oauth/usage` response (subscription quota).
/// The body below is a real capture from the endpoint (2026-06-14, plan account);
/// re-capture and diff if the indicator ever reads wrong after a CLI/API change.
struct SubscriptionUsageTests {
    private static let sample = Data("""
    {
      "five_hour": { "utilization": 37.0, "resets_at": "2026-06-15T04:29:59.851919+00:00" },
      "seven_day": { "utilization": 14.0, "resets_at": "2026-06-21T01:59:59.851939+00:00" },
      "seven_day_oauth_apps": null,
      "seven_day_opus": null,
      "seven_day_sonnet": { "utilization": 0.0, "resets_at": null },
      "extra_usage": { "is_enabled": false, "monthly_limit": null }
    }
    """.utf8)

    @Test func parsesWindowsAndPeak() throws {
        let usage = try SubscriptionUsageFetcher.parse(Self.sample)

        #expect(usage.fiveHour?.utilization == 37.0)
        #expect(usage.fiveHour?.resetsAt != nil)
        #expect(usage.sevenDay?.utilization == 14.0)
        // A null per-model window is absent, not zero.
        #expect(usage.sevenDayOpus == nil)
        // A present window with a null reset keeps the utilization but no date.
        #expect(usage.sevenDaySonnet?.utilization == 0.0)
        #expect(usage.sevenDaySonnet?.resetsAt == nil)
        // The headline tracks the most-constrained window.
        #expect(usage.peakUtilization == 37.0)
    }

    @Test func microsecondResetTimestampParses() throws {
        let usage = try SubscriptionUsageFetcher.parse(Self.sample)
        let resets = try #require(usage.fiveHour?.resetsAt)
        // 2026-06-15T04:29:59.851919Z — verify it landed in the right minute.
        let components = Calendar(identifier: .gregorian)
            .dateComponents(in: TimeZone(identifier: "UTC")!, from: resets)
        #expect(components.year == 2026)
        #expect(components.month == 6)
        #expect(components.day == 15)
        #expect(components.hour == 4)
        #expect(components.minute == 29)
    }

    @Test func malformedBodyThrows() {
        #expect(throws: (any Error).self) {
            try SubscriptionUsageFetcher.parse(Data("not json".utf8))
        }
    }
}
