// Code Custodian File ID: F8A2D3C4-1E5B-4C98-892A-4D7F2A385E91 import Foundation import AppKit import CoreGraphics import ImageIO // MARK: - CLI Argument Parsing // Usage: swift harvest_and_publish_asset.swift [storefront_filename] [prompt...] let args = Array(CommandLine.arguments.dropFirst()) guard args.count >= 3 else { print(""" āŒ Error: Missing required arguments. Usage: swift harvest_and_publish_asset.swift [storefront_filename] [prompt...] Arguments: cdn_url Full CDN URL of the generated asset scene_name Unique scene identifier/filename (without .png) design_id Artistly design ID storefront_filename (Optional) Filename to copy to web storefront, or 'none' / '-' to skip prompt (Optional) Full prompt text recipe """) exit(1) } let rawCdnUrl = args[0] let sceneName = args[1] let designId = args[2] // Clean cdn_url by stripping query parameters (?format=...) let cleanCdnUrl: String if let url = URL(string: rawCdnUrl), var components = URLComponents(url: url, resolvingAgainstBaseURL: false) { components.query = nil cleanCdnUrl = components.string ?? rawCdnUrl } else if let qIndex = rawCdnUrl.firstIndex(of: "?") { cleanCdnUrl = String(rawCdnUrl[.. 3 { let candidate = args[3].trimmingCharacters(in: .whitespacesAndNewlines) if !candidate.isEmpty && candidate.lowercased() != "none" && candidate != "-" { storefrontFilename = candidate } } // Prompt text handling var promptText = "" if args.count > 4 { promptText = args.dropFirst(4).joined(separator: " ").trimmingCharacters(in: .whitespacesAndNewlines) } print("šŸ“‹ Parameter Summary:") print(" Clean CDN URL: \(cleanCdnUrl)") print(" Scene Name: \(sceneName)") print(" Design ID: \(designId)") print(" Storefront File: \(storefrontFilename ?? "(none)")") print(" Prompt: \(promptText.isEmpty ? "(none)" : promptText)") // MARK: - Master Image Download let scenesDir = "/Volumes/FACTORY_SSD/warezfactory/Art_Cannon/Scenes" do { try FileManager.default.createDirectory(atPath: scenesDir, withIntermediateDirectories: true, attributes: nil) } catch { print("āŒ Failed to create Scenes directory: \(error.localizedDescription)") exit(1) } guard let downloadURL = URL(string: cleanCdnUrl) else { print("āŒ Invalid URL: \(cleanCdnUrl)") exit(1) } print("ā¬‡ļø Downloading master asset from: \(cleanCdnUrl)...") var request = URLRequest(url: downloadURL) request.setValue("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36", forHTTPHeaderField: "User-Agent") let semaphore = DispatchSemaphore(value: 0) var downloadedData: Data? = nil var downloadError: Error? = nil let task = URLSession.shared.dataTask(with: request) { data, response, error in downloadedData = data downloadError = error semaphore.signal() } task.resume() semaphore.wait() if let error = downloadError { print("āŒ Download failed: \(error.localizedDescription)") exit(1) } guard let data = downloadedData, !data.isEmpty else { print("āŒ Downloaded data is empty or nil from \(cleanCdnUrl)") exit(1) } let masterPNGPath = "\(scenesDir)/\(sceneName).png" let masterURL = URL(fileURLWithPath: masterPNGPath) do { try data.write(to: masterURL) print("āœ… Master PNG written: \(masterPNGPath)") } catch { print("āŒ Failed to write master PNG: \(error.localizedDescription)") exit(1) } // MARK: - Native 512px Preview Generation guard let imageSource = CGImageSourceCreateWithURL(masterURL as CFURL, nil), let cgImage = CGImageSourceCreateImageAtIndex(imageSource, 0, nil) else { print("āŒ Failed to create CGImage from \(masterPNGPath)") exit(1) } // Measure pixel dimensions from image source var pixelWidth = cgImage.width var pixelHeight = cgImage.height if let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as? [CFString: Any] { if let w = properties[kCGImagePropertyPixelWidth] as? Int { pixelWidth = w } if let h = properties[kCGImagePropertyPixelHeight] as? Int { pixelHeight = h } } let dimensions = "\(pixelWidth)x\(pixelHeight)" print("šŸ“ Asset Dimensions: \(dimensions)") let targetSize: CGFloat = 512.0 let colorSpace = CGColorSpaceCreateDeviceRGB() guard let context = CGContext( data: nil, width: Int(targetSize), height: Int(targetSize), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue ) else { print("āŒ Failed to create CGContext for 512px preview") exit(1) } context.interpolationQuality = .high context.draw(cgImage, in: CGRect(x: 0, y: 0, width: targetSize, height: targetSize)) guard let scaledCG = context.makeImage() else { print("āŒ Failed to create scaled CGImage") exit(1) } let rep = NSBitmapImageRep(cgImage: scaledCG) guard let pngData = rep.representation(using: .png, properties: [:]) else { print("āŒ Failed to convert scaled image to PNG representation") exit(1) } let previewPNGPath = "\(scenesDir)/\(sceneName).preview.png" do { try pngData.write(to: URL(fileURLWithPath: previewPNGPath)) print("āœ… 512px Preview PNG written: \(previewPNGPath)") } catch { print("āŒ Failed to write preview PNG: \(error.localizedDescription)") exit(1) } // MARK: - Companion Metadata JSON Creation let metadataDict: [String: Any] = [ "scene_name": sceneName, "design_id": designId, "cdn_url": cleanCdnUrl, "dimensions": dimensions, "created_at": ISO8601DateFormatter().string(from: Date()), "prompt": promptText ] let metadataPath = "\(scenesDir)/\(sceneName)_metadata.json" do { let jsonData = try JSONSerialization.data(withJSONObject: metadataDict, options: [.prettyPrinted, .sortedKeys]) try jsonData.write(to: URL(fileURLWithPath: metadataPath)) print("āœ… Companion metadata JSON written: \(metadataPath)") } catch { print("āŒ Failed to write metadata JSON: \(error.localizedDescription)") exit(1) } // MARK: - Storefront Publishing (Optional) if let storefrontFilename = storefrontFilename { let storefrontDir = "/Users/dave/warezfactory/web/data/thegroovypanda.com/assets/images/pandas" let storefrontTarget = "\(storefrontDir)/\(storefrontFilename)" let storefrontURL = URL(fileURLWithPath: storefrontTarget) do { try FileManager.default.createDirectory(atPath: storefrontDir, withIntermediateDirectories: true, attributes: nil) if FileManager.default.fileExists(atPath: storefrontTarget) { try FileManager.default.removeItem(at: storefrontURL) } try FileManager.default.copyItem(at: masterURL, to: storefrontURL) print("āœ… Storefront asset published: \(storefrontTarget)") } catch { print("āš ļø Failed to publish asset to storefront: \(error.localizedDescription)") } } // MARK: - Visual Inbound Notification let targetAgent = "Annie 2.0" let inboundPayload: [String: Any] = [ "target_agent": targetAgent, "message": "šŸŽØ Master Asset Harvested: \(sceneName)\nšŸ“ Scenes: \(scenesDir)", "image_path": previewPNGPath ] DistributedNotificationCenter.default().postNotificationName( NSNotification.Name("com.higginsoft.factory.agent.inbound"), object: targetAgent, userInfo: inboundPayload, deliverImmediately: true ) print("šŸ“¢ Inbound notification dispatched to \(targetAgent)") print("✨ Asset harvesting and publishing pipeline completed successfully!")