import Network
import AVFoundation

enum VideoQualityPreset {
    case low, medium, high

    var exportPresetName: String {
        switch self {
        case .low: return AVAssetExportPresetLowQuality
        case .medium: return AVAssetExportPresetMediumQuality
        case .high: return AVAssetExportPresetHighestQuality
        }
    }

    var fileExtension: String {
        return "mp4"
    }

    var mimeType: String {
        return "video/mp4"
    }
}

func isVideoSizeAcceptable(_ data: Data, maxSizeMB: Double = 28.0) -> Bool {
    let sizeMB = Double(data.count) / (1024.0 * 1024.0)
    return sizeMB <= maxSizeMB
}

// MARK: - 動画圧縮処理
func compressVideo(inputURL: URL, preset: VideoQualityPreset, completion: @escaping (Data?) -> Void) {
    let asset = AVAsset(url: inputURL)

    guard let exportSession = AVAssetExportSession(asset: asset, presetName: preset.exportPresetName) else {
        completion(nil)
        return
    }

    let outputURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".mp4")
    exportSession.outputURL = outputURL
    exportSession.outputFileType = .mp4
    exportSession.shouldOptimizeForNetworkUse = true

    exportSession.exportAsynchronously {
        if exportSession.status == .completed {
            if let data = try? Data(contentsOf: outputURL), isVideoSizeAcceptable(data) {
                completion(data)
            } else {
                completion(nil) // サイズオーバー
            }
        } else {
            completion(nil)
        }
    }
}

func selectPresetBasedOnNetwork() -> VideoQualityPreset {
    let monitor = NWPathMonitor()
    var selectedPreset: VideoQualityPreset = .medium

    monitor.pathUpdateHandler = { path in
        if path.status == .satisfied {
            if path.isExpensive {
                selectedPreset = .low // モバイル通信
            } else {
                selectedPreset = .high // Wi-Fi
            }
        } else {
            selectedPreset = .low // オフラインまたは不安定
        }
    }

    let queue = DispatchQueue(label: "NetworkMonitor")
    monitor.start(queue: queue)

    return selectedPreset
}
