// Resize the yōkan default icon and draw the optional Torii artwork on macOS:
// swift -module-cache-path /private/tmp/yokan-icon-cache scripts/generate-app-icons.swift
// The original default artwork is kept in packaging/icons/yokan-source.png.
import AppKit
import Foundation

let root = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
func writePNG(_ path: String, size: Int, draw: (CGContext) -> Void) throws {
    let context = CGContext(data: nil, width: size, height: size, bitsPerComponent: 8,
                            bytesPerRow: size * 4, space: CGColorSpace(name: CGColorSpace.sRGB)!,
                            bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!
    draw(context)
    let bitmap = NSBitmapImageRep(cgImage: context.makeImage()!)
    let target = root.appendingPathComponent(path)
    try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
    try bitmap.representation(using: .png, properties: [:])!.write(to: target)
}
func color(_ hex: UInt32) -> CGColor {
    CGColor(colorSpace: CGColorSpace(name: CGColorSpace.sRGB)!,
            components: [CGFloat((hex >> 16) & 255) / 255, CGFloat((hex >> 8) & 255) / 255,
                         CGFloat(hex & 255) / 255, 1])!
}
let primary = NSImage(contentsOf: root.appendingPathComponent("packaging/icons/yokan-source.png"))!
let original = primary.cgImage(forProposedRect: nil, context: nil, hints: nil)!
func originalPNG(_ path: String, _ size: Int) throws {
    try writePNG(path, size: size) { context in
        context.setFillColor(color(0xFFFFFF)); context.fill(CGRect(x: 0, y: 0, width: size, height: size))
        context.interpolationQuality = .high
        context.draw(original, in: CGRect(x: 0, y: 0, width: size, height: size))
    }
}
func toriiPNG(_ path: String, background: UInt32, foreground: UInt32) throws {
    try writePNG(path, size: 1024) { context in
        context.scaleBy(x: 10.24, y: 10.24)
        context.translateBy(x: 0, y: 100); context.scaleBy(x: 1, y: -1)
        context.setFillColor(color(background)); context.fill(CGRect(x: 0, y: 0, width: 100, height: 100))
        context.setFillColor(color(foreground))
        let beam = CGMutablePath()
        beam.move(to: CGPoint(x: 22, y: 26)); beam.addQuadCurve(to: CGPoint(x: 78, y: 26), control: CGPoint(x: 50, y: 34))
        beam.addLine(to: CGPoint(x: 78, y: 34)); beam.addQuadCurve(to: CGPoint(x: 22, y: 34), control: CGPoint(x: 50, y: 42)); beam.closeSubpath()
        context.addPath(beam); context.fillPath()
        for rect in [CGRect(x: 32, y: 37, width: 8, height: 41), CGRect(x: 60, y: 37, width: 8, height: 41),
                     CGRect(x: 26, y: 44, width: 48, height: 6), CGRect(x: 47, y: 52, width: 6, height: 12)] {
            context.fill(rect)
        }
    }
}
let catalog = "iosApp/Assets.xcassets"
try originalPNG("composeApp/src/commonMain/composeResources/drawable/icon_red.png", 1024)
try originalPNG("composeApp/src/commonMain/composeResources/drawable/mangayomi_icon.png", 1024)
try originalPNG("composeApp/src/androidMain/res/mipmap-anydpi/ic_launcher.png", 192)
try originalPNG("\(catalog)/AppIcon.appiconset/icon.png", 1024)
try toriiPNG("\(catalog)/ToriiLight.appiconset/icon.png", background: 0xFFF6EB, foreground: 0xB81932)
try toriiPNG("\(catalog)/ToriiDark.appiconset/icon.png", background: 0x211B24, foreground: 0xFFBBC4)
try toriiPNG("\(catalog)/ToriiSystem.appiconset/icon.png", background: 0xFFF6EB, foreground: 0xB81932)
try toriiPNG("\(catalog)/ToriiSystem.appiconset/dark.png", background: 0x211B24, foreground: 0xFFBBC4)
try toriiPNG("\(catalog)/ToriiSystem.appiconset/tinted.png", background: 0x202020, foreground: 0xCCCCCC)
try originalPNG("composeApp/src/wasmJsMain/resources/favicon.png", 192)
try originalPNG("packaging/icons/yokan.png", 256)
// ICO container with one PNG image. Windows/jpackage accept the standard compressed image format.
let png = try Data(contentsOf: root.appendingPathComponent("packaging/icons/yokan.png"))
var ico = Data([0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 24, 0])
func appendLE(_ value: UInt32) { ico.append(contentsOf: (0..<4).map { UInt8((value >> ($0 * 8)) & 255) }) }
appendLE(UInt32(png.count)); appendLE(22); ico.append(png)
try ico.write(to: root.appendingPathComponent("packaging/icons/yokan.ico"))
// Temporary macOS iconset source for the ICNS container below.
for size in [16, 32, 128, 256, 512] {
    try originalPNG("packaging/icons/Yokan.iconset/icon_\(size)x\(size).png", size)
    try originalPNG("packaging/icons/Yokan.iconset/icon_\(size)x\(size)@2x.png", size * 2)
}
// An ICNS container can embed standard PNG chunks directly; no iconutil service is needed.
var icnsBody = Data()
for (type, file) in [("icp4", "icon_16x16.png"), ("icp5", "icon_32x32.png"), ("icp6", "icon_32x32@2x.png"),
                     ("ic07", "icon_128x128.png"), ("ic08", "icon_256x256.png"),
                     ("ic09", "icon_512x512.png"), ("ic10", "icon_512x512@2x.png")] {
    let data = try Data(contentsOf: root.appendingPathComponent("packaging/icons/Yokan.iconset/\(file)"))
    icnsBody.append(contentsOf: type.utf8)
    let length = UInt32(data.count + 8)
    icnsBody.append(contentsOf: (0..<4).reversed().map { UInt8((length >> ($0 * 8)) & 255) })
    icnsBody.append(data)
}
var icns = Data("icns".utf8)
let icnsLength = UInt32(icnsBody.count + 8)
icns.append(contentsOf: (0..<4).reversed().map { UInt8((icnsLength >> ($0 * 8)) & 255) })
icns.append(icnsBody)
try icns.write(to: root.appendingPathComponent("packaging/icons/Yokan.icns"))
try FileManager.default.removeItem(at: root.appendingPathComponent("packaging/icons/Yokan.iconset"))
