import Foundation
import SwiftData

@Model
class SavedBattery {
    @Attribute(.unique) var id: UUID
    var name: String
    var nominalVoltage: Double
    var capacityAmpHours: Double
    var usableCapacityOverrideFraction: Double?
    var chargeVoltage: Double?
    var cutOffVoltage: Double?
    var minimumTemperatureCelsius: Double?
    var maximumTemperatureCelsius: Double?
    private var chemistryRawValue: String
    var iconName: String = "battery.100"
    var colorName: String = "blue"
    var system: ElectricalSystem?
    var componentID: String?
    var bomCompletedItemIDs: [String] = []
    var timestamp: Date

    init(
        id: UUID = UUID(),
        name: String,
        nominalVoltage: Double = 12.8,
        capacityAmpHours: Double = 100,
        chemistry: BatteryConfiguration.Chemistry = .lithiumIronPhosphate,
        usableCapacityOverrideFraction: Double? = nil,
        chargeVoltage: Double? = nil,
        cutOffVoltage: Double? = nil,
        minimumTemperatureCelsius: Double? = nil,
        maximumTemperatureCelsius: Double? = nil,
        iconName: String = "battery.100",
        colorName: String = "blue",
        system: ElectricalSystem? = nil,
        componentID: String? = nil,
        bomCompletedItemIDs: [String] = [],
        timestamp: Date = Date()
    ) {
        self.id = id
        self.name = name
        self.nominalVoltage = nominalVoltage
        self.capacityAmpHours = capacityAmpHours
        self.usableCapacityOverrideFraction = usableCapacityOverrideFraction
        self.chargeVoltage = chargeVoltage
        self.cutOffVoltage = cutOffVoltage
        self.minimumTemperatureCelsius = minimumTemperatureCelsius
        self.maximumTemperatureCelsius = maximumTemperatureCelsius
        self.chemistryRawValue = chemistry.rawValue
        self.iconName = iconName
        self.colorName = colorName
        self.system = system
        self.componentID = componentID
        self.bomCompletedItemIDs = bomCompletedItemIDs
        self.timestamp = timestamp
    }

    var chemistry: BatteryConfiguration.Chemistry {
        get {
            BatteryConfiguration.Chemistry(rawValue: chemistryRawValue) ?? .lithiumIronPhosphate
        }
        set {
            chemistryRawValue = newValue.rawValue
        }
    }

    var energyWattHours: Double {
        nominalVoltage * capacityAmpHours
    }

    var usableCapacityAmpHours: Double {
        let fraction: Double
        if let override = usableCapacityOverrideFraction {
            fraction = max(0, min(1, override))
        } else {
            fraction = chemistry.usableCapacityFraction
        }
        return capacityAmpHours * fraction
    }

    var usableEnergyWattHours: Double {
        usableCapacityAmpHours * nominalVoltage
    }
}
