import Foundation
import AVFoundation
import CoreGraphics
import CoreVideo
import ImageIO

enum FrameVideoError: Error {
    case missingFrame(String)
    case unreadableImage(URL)
    case cannotCreateBuffer(CVReturn)
    case cannotCreateContext
    case cannotLockBuffer(CVReturn)
    case invalidSettings
    case outputAlreadyExists
    case unsupportedSettings
    case encodingFailed
}

func exampleFrameURLs() throws -> [URL] {
    let names: [String] = (1...10).map({ (number: Int) -> String in
        String(format: "frame-%02d", number)
    })
    let urls: [URL] = try names.map({ (name: String) throws -> URL in
        guard let url: URL = Bundle.main.url(
            forResource: name,
            withExtension: "png",
            subdirectory: "Frames"
        ) else {
            throw FrameVideoError.missingFrame(name)
        }
        return url
    })
    return urls
}

func loadFrame(imageURL: URL, maximumPixelSize: Int) throws -> CGImage {
    guard let source: CGImageSource = CGImageSourceCreateWithURL(
        imageURL as CFURL,
        nil
    ) else {
        throw FrameVideoError.unreadableImage(imageURL)
    }
    let options: [CFString: Any] = [
        kCGImageSourceCreateThumbnailFromImageAlways: true,
        kCGImageSourceCreateThumbnailWithTransform: true,
        kCGImageSourceThumbnailMaxPixelSize: maximumPixelSize
    ]
    guard let image: CGImage = CGImageSourceCreateThumbnailAtIndex(
        source,
        0,
        options as CFDictionary
    ) else {
        throw FrameVideoError.unreadableImage(imageURL)
    }
    return image
}

func makePixelBuffer(
    image: CGImage,
    width: Int,
    height: Int
) throws -> CVPixelBuffer {
    let attributes: [CFString: Any] = [
        kCVPixelBufferCGImageCompatibilityKey: true,
        kCVPixelBufferCGBitmapContextCompatibilityKey: true
    ]
    var allocatedBuffer: CVPixelBuffer? = nil
    let creationResult: CVReturn = CVPixelBufferCreate(
        kCFAllocatorDefault,
        width,
        height,
        kCVPixelFormatType_32BGRA,
        attributes as CFDictionary,
        &allocatedBuffer
    )
    guard creationResult == kCVReturnSuccess,
          let buffer: CVPixelBuffer = allocatedBuffer else {
        throw FrameVideoError.cannotCreateBuffer(creationResult)
    }

    let lockResult: CVReturn = CVPixelBufferLockBaseAddress(buffer, [])
    guard lockResult == kCVReturnSuccess else {
        throw FrameVideoError.cannotLockBuffer(lockResult)
    }
    defer { CVPixelBufferUnlockBaseAddress(buffer, []) }

    guard let context: CGContext = CGContext(
        data: CVPixelBufferGetBaseAddress(buffer),
        width: width,
        height: height,
        bitsPerComponent: 8,
        bytesPerRow: CVPixelBufferGetBytesPerRow(buffer),
        space: CGColorSpace(name: CGColorSpace.sRGB)!,
        bitmapInfo: (
            CGBitmapInfo.byteOrder32Little.rawValue |
            CGImageAlphaInfo.premultipliedFirst.rawValue
        )
    ) else {
        throw FrameVideoError.cannotCreateContext
    }

    let bounds: CGRect = CGRect(x: 0, y: 0, width: width, height: height)
    context.setFillColor(CGColor(gray: 0, alpha: 1))
    context.fill(bounds)

    let scale: CGFloat = min(
        CGFloat(width) / CGFloat(image.width),
        CGFloat(height) / CGFloat(image.height)
    )
    let drawnWidth: CGFloat = CGFloat(image.width) * scale
    let drawnHeight: CGFloat = CGFloat(image.height) * scale
    let imageRect: CGRect = CGRect(
        x: (CGFloat(width) - drawnWidth) / 2,
        y: (CGFloat(height) - drawnHeight) / 2,
        width: drawnWidth,
        height: drawnHeight
    )
    context.draw(image, in: imageRect)
    return buffer
}

// Mutable state is accessed only on the private serial queue.
final class MP4CallbackExporter: @unchecked Sendable {
    private let imageURLs: [URL]
    private let outputURL: URL
    private let width: Int
    private let height: Int
    private let framesPerSecond: Int32
    private let writer: AVAssetWriter
    private let input: AVAssetWriterInput
    private let adaptor: AVAssetWriterInputPixelBufferAdaptor
    private let queue: DispatchQueue = DispatchQueue(label: "MP4CallbackExporter")
    private let completionQueue: DispatchQueue
    private let completion: @Sendable (Result<URL, Error>) -> Void
    private var index: Int = 0
    private var isFinishing: Bool = false
    private var keepAlive: MP4CallbackExporter? = nil

    static func export(
        imageURLs: [URL],
        outputURL: URL,
        width: Int,
        height: Int,
        framesPerSecond: Int32,
        completionQueue: DispatchQueue,
        completion: @escaping @Sendable (Result<URL, Error>) -> Void
    ) throws {
        let exporter: MP4CallbackExporter = try MP4CallbackExporter(
            imageURLs: imageURLs,
            outputURL: outputURL,
            width: width,
            height: height,
            framesPerSecond: framesPerSecond,
            completionQueue: completionQueue,
            completion: completion
        )
        exporter.queue.async(execute: { () -> Void in
            exporter.beginWriting()
        })
    }

    private init(
        imageURLs: [URL],
        outputURL: URL,
        width: Int,
        height: Int,
        framesPerSecond: Int32,
        completionQueue: DispatchQueue,
        completion: @escaping @Sendable (Result<URL, Error>) -> Void
    ) throws {
        guard !imageURLs.isEmpty, width > 0, height > 0,
              width.isMultiple(of: 2), height.isMultiple(of: 2),
              framesPerSecond > 0 else {
            throw FrameVideoError.invalidSettings
        }
        guard !FileManager.default.fileExists(atPath: outputURL.path) else {
            throw FrameVideoError.outputAlreadyExists
        }
        let settings: [String: Any] = [
            AVVideoCodecKey: AVVideoCodecType.h264,
            AVVideoWidthKey: width,
            AVVideoHeightKey: height
        ]
        let writer: AVAssetWriter = try AVAssetWriter(outputURL: outputURL, fileType: .mp4)
        guard writer.canApply(outputSettings: settings, forMediaType: .video) else {
            throw FrameVideoError.unsupportedSettings
        }
        let input: AVAssetWriterInput = AVAssetWriterInput(
            mediaType: .video,
            outputSettings: settings
        )
        input.expectsMediaDataInRealTime = false
        guard writer.canAdd(input) else {
            throw FrameVideoError.unsupportedSettings
        }
        let adaptor: AVAssetWriterInputPixelBufferAdaptor = AVAssetWriterInputPixelBufferAdaptor(
            assetWriterInput: input,
            sourcePixelBufferAttributes: nil
        )
        writer.add(input)

        self.imageURLs = imageURLs
        self.outputURL = outputURL
        self.width = width
        self.height = height
        self.framesPerSecond = framesPerSecond
        self.writer = writer
        self.input = input
        self.adaptor = adaptor
        self.completionQueue = completionQueue
        self.completion = completion
    }

    private func beginWriting() {
        self.keepAlive = self
        guard self.writer.startWriting() else {
            self.complete(result: .failure(self.writer.error ?? FrameVideoError.encodingFailed))
            return
        }
        self.writer.startSession(atSourceTime: .zero)
        self.input.requestMediaDataWhenReady(
            on: self.queue,
            using: { [weak self] () -> Void in
                self?.appendReadyFrames()
            }
        )
    }

    private func appendReadyFrames() {
        guard !self.isFinishing else { return }
        guard self.writer.status == .writing else {
            self.complete(result: .failure(self.writer.error ?? FrameVideoError.encodingFailed))
            return
        }

        do {
            while self.input.isReadyForMoreMediaData && self.index < self.imageURLs.count {
                let image: CGImage = try loadFrame(
                    imageURL: self.imageURLs[self.index],
                    maximumPixelSize: max(self.width, self.height)
                )
                let buffer: CVPixelBuffer = try makePixelBuffer(
                    image: image,
                    width: self.width,
                    height: self.height
                )
                let timestamp: CMTime = CMTime(
                    value: Int64(self.index),
                    timescale: self.framesPerSecond
                )
                guard self.adaptor.append(buffer, withPresentationTime: timestamp) else {
                    throw self.writer.error ?? FrameVideoError.encodingFailed
                }
                self.index += 1
            }

            if self.index == self.imageURLs.count {
                self.isFinishing = true
                let endTime: CMTime = CMTime(
                    value: Int64(self.imageURLs.count),
                    timescale: self.framesPerSecond
                )
                self.writer.endSession(atSourceTime: endTime)
                self.input.markAsFinished()
                self.writer.finishWriting(completionHandler: { () -> Void in
                    self.queue.async(execute: { () -> Void in
                        if self.writer.status == .completed {
                            self.complete(result: .success(self.outputURL))
                        } else {
                            self.complete(result: .failure(self.writer.error ?? FrameVideoError.encodingFailed))
                        }
                    })
                })
            }
        } catch {
            self.complete(result: .failure(error))
        }
    }

    private func complete(result: Result<URL, Error>) {
        self.isFinishing = true
        if case .failure = result {
            self.writer.cancelWriting()
            try? FileManager.default.removeItem(at: self.outputURL)
        }
        self.completionQueue.async(execute: { () -> Void in
            self.completion(result)
        })
        self.keepAlive = nil
    }
}

func exportExampleWithCompletion(
    completionQueue: DispatchQueue,
    completion: @escaping @Sendable (Result<URL, Error>) -> Void
) throws {
    let frames: [URL] = try exampleFrameURLs()
    let folder: URL = FileManager.default.temporaryDirectory
    let filename: String = "frames-\(UUID().uuidString).mp4"
    let outputURL: URL = folder.appendingPathComponent(filename)

    try MP4CallbackExporter.export(
        imageURLs: frames,
        outputURL: outputURL,
        width: 100,
        height: 100,
        framesPerSecond: 2,
        completionQueue: completionQueue,
        completion: completion
    )
}
