import Alamofire
import Foundation
import LilithAgentCore
import LilithLogging
import MacSyncShared
import SwiftyJSON

private let log = AppLogger.logger(for: "IReminder.API")

// MARK: - Payload Types

public struct SyncReminderCalendarPayload {
    public let calendarIdentifier: String
    public let title: String
    public let source: String
    public let color: String

    public init(calendarIdentifier: String, title: String, source: String, color: String) {
        self.calendarIdentifier = calendarIdentifier
        self.title = title
        self.source = source
        self.color = color
    }

    var dictionary: [String: Any?] {
        [
            "calendarIdentifier": calendarIdentifier,
            "title": title,
            "source": source,
            "color": color,
        ]
    }
}

/// Inbound (Mac → server) reminder payload. Field set matches
/// `src/server/src/surfaces/client/ireminders.ts` Zod schema; `createdAt` is
/// intentionally omitted because the server does not accept it.
public struct SyncReminderPayload {
    public let reminderIdentifier: String
    public let calendarIdentifier: String
    public let title: String?
    public let notes: String?
    public let dueDate: String?
    public let priority: Int?
    public let isCompleted: Bool
    public let modifiedAt: String?

    public init(
        reminderIdentifier: String,
        calendarIdentifier: String,
        title: String?,
        notes: String?,
        dueDate: String?,
        priority: Int?,
        isCompleted: Bool,
        modifiedAt: String?
    ) {
        self.reminderIdentifier = reminderIdentifier
        self.calendarIdentifier = calendarIdentifier
        self.title = title
        self.notes = notes
        self.dueDate = dueDate
        self.priority = priority
        self.isCompleted = isCompleted
        self.modifiedAt = modifiedAt
    }

    var dictionary: [String: Any?] {
        [
            "reminderIdentifier": reminderIdentifier,
            "calendarIdentifier": calendarIdentifier,
            "title": title,
            "notes": notes,
            "dueDate": dueDate,
            "priority": priority,
            "isCompleted": isCompleted,
            "modifiedAt": modifiedAt,
        ]
    }
}

public struct IReminderStatsResponse {
    public let totalReminders: Int
    public let lastSyncAt: Date?

    public init(totalReminders: Int, lastSyncAt: Date?) {
        self.totalReminders = totalReminders
        self.lastSyncAt = lastSyncAt
    }
}

// MARK: - Protocol

public protocol IReminderAPIClientProtocol: AnyObject, Sendable {
    var isAuthenticated: Bool { get }
    func syncReminders(_ payloads: [SyncReminderPayload]) async throws -> Int
    func getStats() async throws -> IReminderStatsResponse
    func getPendingSends() async throws -> [PendingReminderSend]
    func reportSendResult(id: String, status: String, error: String?) async throws
}

// MARK: - APIClient

public final class APIClient: BaseAPIClient, IReminderAPIClientProtocol, @unchecked Sendable {
    public static let shared: APIClient = {
        APIClient(baseURL: macSyncResolveServerURL(), keychain: macSyncSharedKeychain)
    }()

    public var isAuthenticated: Bool {
        (try? getAuthToken()) != nil
    }

    public func syncReminders(_ payloads: [SyncReminderPayload]) async throws -> Int {
        let params: [String: Any] = ["reminders": payloads.map { $0.dictionary }]
        let data = try await authenticatedRequest("/client/ireminders/sync", method: .post, parameters: params)
        let json = JSON(data)
        guard json["success"].boolValue else {
            let msg = json["error"]["message"].stringValue
            throw APIError.serverError(statusCode: json["statusCode"].intValue,
                                       message: msg.isEmpty ? "Server error" : msg)
        }
        let synced = json["data"]["synced"].intValue
        log.info("syncReminders synced=\(synced)")
        return synced
    }

    public func getStats() async throws -> IReminderStatsResponse {
        let data = try await authenticatedRequest("/client/ireminders/stats", method: .get)
        let json = JSON(data)
        guard json["success"].boolValue else {
            throw APIError.serverError(statusCode: 0, message: json["error"]["message"].stringValue)
        }
        return IReminderStatsResponse(
            totalReminders: json["data"]["totalReminders"].intValue,
            lastSyncAt: json["data"]["lastSyncAt"].string.flatMap { ISO8601DateFormatter().date(from: $0) }
        )
    }

    // MARK: - Send Queue

    public func getPendingSends() async throws -> [PendingReminderSend] {
        let data = try await authenticatedRequest("/client/ireminders/send-queue/pending", method: .get)
        let json = JSON(data)
        guard json["success"].boolValue else {
            throw APIError.serverError(statusCode: 0, message: json["error"]["message"].stringValue)
        }
        return json["data"]["items"].arrayValue.map { item in
            PendingReminderSend(
                id: item["id"].stringValue,
                action: item["action"].stringValue,
                payload: ReminderSendPayload(
                    reminderIdentifier: item["payload"]["reminderIdentifier"].string,
                    calendarIdentifier: item["payload"]["calendarIdentifier"].string,
                    title: item["payload"]["title"].string,
                    notes: item["payload"]["notes"].string,
                    dueDate: item["payload"]["dueDate"].string,
                    priority: item["payload"]["priority"].int,
                    isCompleted: item["payload"]["isCompleted"].bool
                ),
                createdAt: item["createdAt"].stringValue
            )
        }
    }

    public func reportSendResult(id: String, status: String, error: String?) async throws {
        var params: [String: Any] = ["status": status]
        if let err = error { params["error"] = err }
        let data = try await authenticatedRequest("/client/ireminders/send-queue/\(id)/result", method: .post, parameters: params)
        let json = JSON(data)
        guard json["success"].boolValue else {
            throw APIError.serverError(statusCode: 0, message: json["error"]["message"].stringValue)
        }
    }
}
