import AppKit
import CoreText
import Foundation
import ImageIO

let size = 180
let outputURL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath).appendingPathComponent("assets/icons/apple-touch-icon.png")
let fontURL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath).appendingPathComponent("assets/fonts/material-symbols-outlined.ttf")
guard CTFontManagerRegisterFontsForURL(fontURL as CFURL, .process, nil) else {
    fputs("Could not register Material Symbols font\n", stderr)
    exit(1)
}

let colorSpace = CGColorSpaceCreateDeviceRGB()
let bytesPerRow = size * 4
guard let context = CGContext(data: nil, width: size, height: size, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else {
    fputs("Could not create image context\n", stderr)
    exit(1)
}

context.clear(CGRect(x: 0, y: 0, width: size, height: size))
context.setFillColor(red: 77 / 255, green: 131 / 255, blue: 215 / 255, alpha: 1)
context.addPath(CGPath(roundedRect: CGRect(x: 0, y: 0, width: size, height: size), cornerWidth: 42, cornerHeight: 42, transform: nil))
context.fillPath()

let font = CTFontCreateWithName("Material Symbols Outlined" as CFString, 112, nil)
let attributes: [NSAttributedString.Key: Any] = [
    NSAttributedString.Key(kCTFontAttributeName as String): font,
    NSAttributedString.Key(kCTForegroundColorAttributeName as String): CGColor(red: 1, green: 1, blue: 1, alpha: 1)
]
let line = CTLineCreateWithAttributedString(NSAttributedString(string: "wallet", attributes: attributes))
let bounds = CTLineGetBoundsWithOptions(line, [])
context.textPosition = CGPoint(x: (CGFloat(size) - bounds.width) / 2 - bounds.minX, y: (CGFloat(size) - bounds.height) / 2 - bounds.minY - 1)
CTLineDraw(line, context)

guard let image = context.makeImage(), let destination = CGImageDestinationCreateWithURL(outputURL as CFURL, "public.png" as CFString, 1, nil) else {
    fputs("Could not create PNG destination\n", stderr)
    exit(1)
}
CGImageDestinationAddImage(destination, image, [kCGImagePropertyPNGDictionary as String: [kCGImagePropertyPNGInterlaceType as String: 0]] as CFDictionary)
guard CGImageDestinationFinalize(destination) else {
    fputs("Could not write PNG\n", stderr)
    exit(1)
}
