//
//  UITestSampleData.swift
//  Cable
//  Created by Stefan Lange-Hegermann on 06.10.25.

import Foundation
import SwiftData

enum UITestSampleData {
    static let sampleArgument = "--uitest-sample-data"
    static let resetArgument = "--uitest-reset-data"

    static func handleLaunchArguments(container: ModelContainer) {
#if DEBUG
        let arguments = ProcessInfo.processInfo.arguments
        NSLog("UITestSampleData arguments: %@", arguments.joined(separator: ", "))
        guard arguments.contains(sampleArgument) || arguments.contains(resetArgument) else { return }

        let context = ModelContext(container)

        do {
            if arguments.contains(resetArgument) {
                NSLog("UITestSampleData resetting data store")
                try clearExistingData(in: context)
            }

            if arguments.contains(sampleArgument) {
                NSLog("UITestSampleData seeding sample data")
                if !arguments.contains(resetArgument) {
                    try clearExistingData(in: context)
                }
                try seedSampleData(in: context)
            }

            if context.hasChanges {
                try context.save()
                NSLog("UITestSampleData save completed")
            }
        } catch {
            assertionFailure("Failed to prepare UI test data: \(error)")
        }
#endif
    }
}

#if DEBUG
extension UITestSampleData {
    static func clearExistingData(in context: ModelContext) throws {
        let systemDescriptor = FetchDescriptor<ElectricalSystem>()
        let loadDescriptor = FetchDescriptor<SavedLoad>()
        let batteryDescriptor = FetchDescriptor<SavedBattery>()
        let chargerDescriptor = FetchDescriptor<SavedCharger>()
        let itemDescriptor = FetchDescriptor<Item>()

        let systems = try context.fetch(systemDescriptor)
        let loads = try context.fetch(loadDescriptor)
        let batteries = try context.fetch(batteryDescriptor)
        let chargers = try context.fetch(chargerDescriptor)
        let items = try context.fetch(itemDescriptor)

        systems.forEach { context.delete($0) }
        loads.forEach { context.delete($0) }
        batteries.forEach { context.delete($0) }
        chargers.forEach { context.delete($0) }
        items.forEach { context.delete($0) }
    }

    static func seedSampleData(in context: ModelContext) throws {
        let adventureVan = ElectricalSystem(
            name: String(localized: "sample.system.rv.name", comment: "Sample data name for the adventure van system"),
            location: String(localized: "sample.system.rv.location", comment: "Sample data location for the adventure van system"),
            iconName: "bus",
            colorName: "orange"
        )
        adventureVan.timestamp = Date(timeIntervalSinceReferenceDate: 3000)
        adventureVan.targetRuntimeHours = 24
        adventureVan.targetChargeTimeHours = 3

        let workshopBench = ElectricalSystem(
            name: String(localized: "sample.system.workshop.name", comment: "Sample data name for the workshop system"),
            location: String(localized: "sample.system.workshop.location", comment: "Sample data location for the workshop system"),
            iconName: "wrench.adjustable",
            colorName: "teal"
        )
        workshopBench.timestamp = Date(timeIntervalSinceReferenceDate: 2000)

        context.insert(adventureVan)
        context.insert(workshopBench)

        let vanFridge = SavedLoad(
            name: String(localized: "sample.load.fridge.name", comment: "Sample data load name for a compressor fridge"),
            voltage: 12.0,
            current: 4.2,
            power: 50.0,
            length: 6.0,
            crossSection: 6.0,
            iconName: "snowflake",
            colorName: "blue",
            isWattMode: true,
            system: adventureVan,
            bomCompletedItemIDs: ["component", "cable-red", "fuse"],
            identifier: "sample.load.fridge"
        )
        vanFridge.timestamp = Date(timeIntervalSinceReferenceDate: 1100)

        let vanLighting = SavedLoad(
            name: String(localized: "sample.load.lighting.name", comment: "Sample data load name for LED strip lighting"),
            voltage: 12.0,
            current: 2.0,
            power: 24.0,
            length: 10.0,
            crossSection: 2.5,
            iconName: "lightbulb",
            colorName: "yellow",
            isWattMode: false,
            system: adventureVan,
            bomCompletedItemIDs: ["component", "cable-black"],
            identifier: "sample.load.lighting"
        )
        vanLighting.timestamp = Date(timeIntervalSinceReferenceDate: 1200)

        let workshopCompressor = SavedLoad(
            name: String(localized: "sample.load.compressor.name", comment: "Sample data load name for an air compressor"),
            voltage: 120.0,
            current: 8.0,
            power: 960.0,
            length: 15.0,
            crossSection: 16.0,
            iconName: "hammer",
            colorName: "red",
            isWattMode: true,
            system: workshopBench,
            identifier: "sample.load.compressor"
        )
        workshopCompressor.timestamp = Date(timeIntervalSinceReferenceDate: 2100)

        let workshopCharger = SavedLoad(
            name: String(localized: "sample.load.charger.name", comment: "Sample data load name for a tool charger"),
            voltage: 120.0,
            current: 3.5,
            power: 420.0,
            length: 8.0,
            crossSection: 10.0,
            iconName: "battery.100",
            colorName: "green",
            isWattMode: false,
            system: workshopBench,
            identifier: "sample.load.charger"
        )
        workshopCharger.timestamp = Date(timeIntervalSinceReferenceDate: 2200)

        [vanFridge, vanLighting, workshopCompressor, workshopCharger].forEach { context.insert($0) }

        let vanHouseBattery = SavedBattery(
            name: String(localized: "sample.battery.rv.name", comment: "Sample data battery name for the adventure van system"),
            nominalVoltage: 12.8,
            capacityAmpHours: 200.0,
            chemistry: .lithiumIronPhosphate,
            chargeVoltage: 14.4,
            cutOffVoltage: 10.8,
            minimumTemperatureCelsius: -20,
            maximumTemperatureCelsius: 60,
            iconName: "battery.100.bolt",
            colorName: "purple",
            system: adventureVan,
            bomCompletedItemIDs: ["battery"]
        )
        vanHouseBattery.timestamp = Date(timeIntervalSinceReferenceDate: 1250)

        let workshopBackupBattery = SavedBattery(
            name: String(localized: "sample.battery.workshop.name", comment: "Sample data battery name for the workshop system"),
            nominalVoltage: 24.0,
            capacityAmpHours: 100.0,
            chemistry: .agm,
            chargeVoltage: 28.8,
            cutOffVoltage: 21.0,
            minimumTemperatureCelsius: -10,
            maximumTemperatureCelsius: 50,
            iconName: "battery.75",
            colorName: "gray",
            system: workshopBench
        )
        workshopBackupBattery.timestamp = Date(timeIntervalSinceReferenceDate: 2300)

        [vanHouseBattery, workshopBackupBattery].forEach { context.insert($0) }

        let shoreCharger = SavedCharger(
            name: String(localized: "sample.charger.shore.name", comment: "Sample data name for a shore power charger"),
            inputVoltage: LocaleDefaults.mainsVoltage,
            outputVoltage: 14.4,
            maxCurrentAmps: 40.0,
            maxPowerWatts: 600.0,
            iconName: "powerplug",
            colorName: "orange",
            system: adventureVan,
            bomCompletedItemIDs: ["charger"],
            identifier: "sample.charger.shore"
        )
        shoreCharger.timestamp = Date(timeIntervalSinceReferenceDate: 1300)

        let alternatorCharger = SavedCharger(
            name: String(localized: "sample.charger.dcdc.name", comment: "Sample data name for a DC-DC charger"),
            inputVoltage: 12.8,
            outputVoltage: 14.2,
            maxCurrentAmps: 30.0,
            maxPowerWatts: 0.0,
            iconName: "bolt.badge.clock",
            colorName: "blue",
            system: adventureVan,
            identifier: "sample.charger.dcdc",
            powerSourceType: "alternator"
        )
        alternatorCharger.timestamp = Date(timeIntervalSinceReferenceDate: 1350)

        let benchCharger = SavedCharger(
            name: String(localized: "sample.charger.workbench.name", comment: "Sample data name for a workbench charger"),
            inputVoltage: 120.0,
            outputVoltage: 14.6,
            maxCurrentAmps: 25.0,
            maxPowerWatts: 365.0,
            iconName: "bolt",
            colorName: "green",
            system: workshopBench,
            identifier: "sample.charger.workbench"
        )
        benchCharger.timestamp = Date(timeIntervalSinceReferenceDate: 2250)

        [shoreCharger, alternatorCharger, benchCharger].forEach { context.insert($0) }
    }
}
#endif
