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
}

@available(iOS 26.0, macOS 26.0, *)
func exportMP4(
    imageURLs: [URL],
    outputURL: URL,
    width: Int,
    height: Int,
    framesPerSecond: Int32
) async throws
{
    guard !imageURLs.isEmpty,
          width > 0,
          height > 0,
          width.isMultiple(of: 2),
          height.isMultiple(of: 2),
          framesPerSecond > 0
    else {
        throw FrameVideoError.invalidSettings
    }

    let fileManager: FileManager = FileManager.default

    guard !fileManager.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 receiver: AVAssetWriterInput.PixelBufferReceiver = writer.inputPixelBufferReceiver(
        for: input,
        pixelBufferAttributes: nil
    )

    do {
        try writer.start()
        writer.startSession(atSourceTime: .zero)

        var index: Int = 0

        while index < imageURLs.count {
            try Task.checkCancellation()
            let image: CGImage = try loadFrame(
                imageURL: imageURLs[index],
                maximumPixelSize: max(width, height)
            )
            let buffer: CVPixelBuffer = try makePixelBuffer(
                image: image,
                width: width,
                height: height
            )
            let timestamp: CMTime = CMTime(
                value: Int64(index),
                timescale: framesPerSecond
            )
            let readOnlyBuffer: CVReadOnlyPixelBuffer = CVReadOnlyPixelBuffer(unsafeBuffer: buffer)
            try await receiver.append(readOnlyBuffer, with: timestamp)
            index += 1
        }

        let endTime: CMTime = CMTime(
            value: Int64(imageURLs.count),
            timescale: framesPerSecond
        )
        writer.endSession(atSourceTime: endTime)
        receiver.finish()
        await writer.finishWriting()

        guard writer.status == .completed else {
            throw writer.error ?? FrameVideoError.encodingFailed
        }
    }
    catch {
        writer.cancelWriting()
        try? fileManager.removeItem(at: outputURL)
        throw error
    }

}

@available(iOS 26.0, macOS 26.0, *)
func exportExample() async throws -> URL {
    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 await exportMP4(
        imageURLs: frames,
        outputURL: outputURL,
        width: 100,
        height: 100,
        framesPerSecond: 2
    )

    return outputURL
}
