import Foundation import ImageIO /// Agentur-Check: what is checked before photos go to an agency server. public struct PreflightOptions: Codable, Hashable, Sendable { /// Field ids that must not be empty (error) public var requiredFields: [String] = ["caption", "headline", "creator", "copyright", "city", "country", "dateCreated"] /// First caption line empty (the line for the people in the PM template) → warning public var warnEmptyFirstLine = true /// Dates like 02.11.2026 in headline/caption must match the capture date (old template reused?) public var checkDates = true /// IIM byte limits (agencies truncate) public var checkLengths = true /// Jersey suggestions not yet accepted/dismissed public var checkOpenSuggestions = true /// Minimum long edge in pixels (0 = off) public var minLongEdge = 0 public init() {} enum CodingKeys: String, CodingKey { case requiredFields, warnEmptyFirstLine, checkDates, checkLengths, checkOpenSuggestions, minLongEdge } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) let d = PreflightOptions() requiredFields = (try? c.decode([String].self, forKey: .requiredFields)) ?? d.requiredFields warnEmptyFirstLine = (try? c.decode(Bool.self, forKey: .warnEmptyFirstLine)) ?? d.warnEmptyFirstLine checkDates = (try? c.decode(Bool.self, forKey: .checkDates)) ?? d.checkDates checkLengths = (try? c.decode(Bool.self, forKey: .checkLengths)) ?? d.checkLengths checkOpenSuggestions = (try? c.decode(Bool.self, forKey: .checkOpenSuggestions)) ?? d.checkOpenSuggestions minLongEdge = (try? c.decode(Int.self, forKey: .minLongEdge)) ?? d.minLongEdge } } public enum PreflightSeverity: String, Codable, Sendable, Comparable { case warning, error public static func < (a: PreflightSeverity, b: PreflightSeverity) -> Bool { a == .warning && b == .error } } public struct PreflightIssue: Hashable, Identifiable, Sendable { public var id: String { severity.rawValue + "|" + message } public var severity: PreflightSeverity public var message: String /// field the issue belongs to (to jump to it), nil = whole image public var fieldID: String? public init(_ severity: PreflightSeverity, _ message: String, field: String? = nil) { self.severity = severity; self.message = message; self.fieldID = field } } public enum Preflight { /// Reads the actual upload files without decoding their pixels. static func imageSizeIssues(files: [URL], minimum: Int) -> [PreflightIssue] { guard minimum > 0 else { return [] } // RAWs are not what the agency gets and ImageIO may not know a new camera yet → only the delivered images return files.filter { !FileKind(url: $0).isRawLike }.compactMap { file in guard let source = CGImageSourceCreateWithURL(file as CFURL, nil), let info = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any], let width = info[kCGImagePropertyPixelWidth] as? Int, let height = info[kCGImagePropertyPixelHeight] as? Int else { return PreflightIssue(.error, "\(file.lastPathComponent): Bildgröße nicht lesbar") } let edge = max(width, height) guard edge < minimum else { return nil } return PreflightIssue(.error, "\(file.lastPathComponent): \(edge) px lange Kante (mindestens \(minimum) px)") } } /// Checks one photo. `openSuggestions` = codes/names of jersey suggestions still open. public static func check(iptc: IPTCValues, exif: [String: String], captureDate: Date?, codes: CodeReplacements, options: PreflightOptions, openSuggestions: [String] = [], uploadFiles: [URL]? = nil) -> [PreflightIssue] { var issues: [PreflightIssue] = [] // 1. required fields for id in options.requiredFields { guard let f = IPTCField.byID[id] else { continue } let value = f.kind == .list ? iptc.list(f).joined() : (iptc.text[id] ?? "") if value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { issues.append(PreflightIssue(.error, "Pflichtfeld leer: \(f.label)", field: id)) } } let caption = iptc.text["caption"] ?? "" // 2. first caption line (people line of the template) still empty if options.warnEmptyFirstLine, !caption.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { let first = caption.components(separatedBy: .newlines).first ?? "" if first.trimmingCharacters(in: .whitespaces).isEmpty { issues.append(PreflightIssue(.warning, "Erste Zeile der Beschreibung ist leer – Person vergessen?", field: "caption")) } } // 3. unresolved variables / codes in any text var allTexts: [(IPTCField, String)] = [] for f in IPTCField.all { if f.kind == .list { for v in iptc.list(f) { allTexts.append((f, v)) } } else if let v = iptc.text[f.id], !v.isEmpty { allTexts.append((f, v)) } } var reported = Set() for (f, text) in allTexts { for v in unresolvedVariables(in: text) where reported.insert("var" + v).inserted { issues.append(PreflightIssue(.error, "Variable nicht ersetzt: \(v) (\(f.label))", field: f.id)) } for c in unresolvedDelimiterCodes(in: text, delimiter: codes.delimiter) where reported.insert("code" + c).inserted { issues.append(PreflightIssue(.error, "Code nicht ersetzt: \(c) (\(f.label))", field: f.id)) } } for (f, text) in allTexts where ["caption", "headline", "personInImage", "objectName"].contains(f.id) { for token in bareCodes(in: text, codes: codes) where reported.insert("bare" + token).inserted { issues.append(PreflightIssue(.warning, "„\(token)“ ist ein Code und steht noch im Text (\(f.label))", field: f.id)) } } // 4. dates in headline / caption vs. capture date if options.checkDates, let captureDate { let cal = Calendar(identifier: .gregorian) for id in ["headline", "caption", "event"] { guard let text = iptc.text[id] else { continue } for d in dates(in: text) { let days = abs(cal.dateComponents([.day], from: cal.startOfDay(for: d), to: cal.startOfDay(for: captureDate)).day ?? 0) // ±1 day: late kick-off after midnight if days > 1 { let f = DateFormatter(); f.dateFormat = "dd.MM.yyyy" let label = IPTCField.byID[id]?.label ?? id issues.append(PreflightIssue(.warning, "Datum \(f.string(from: d)) in „\(label)“ passt nicht zur Aufnahme (\(f.string(from: captureDate))) – alte Vorlage?", field: id)) } } } } // 5. IIM lengths if options.checkLengths { for f in IPTCField.all { guard let max = f.iimMaxBytes, f.iimTag != nil, f.id != "dateCreated" else { continue } if f.kind == .list { for v in iptc.list(f) where v.utf8.count > max { issues.append(PreflightIssue(.warning, "\(f.label) „\(v.prefix(30))…“ länger als \(max) Bytes – wird gekürzt", field: f.id)) } } else if let v = iptc.text[f.id], v.utf8.count > max { issues.append(PreflightIssue(.warning, "\(f.label) zu lang (\(v.utf8.count)/\(max) Bytes) – wird gekürzt", field: f.id)) } } } // 6. open jersey suggestions if options.checkOpenSuggestions, !openSuggestions.isEmpty { issues.append(PreflightIssue(.warning, "Spieler-Vorschlag noch offen: \(openSuggestions.joined(separator: ", "))")) } // 7. image size if let uploadFiles { issues += imageSizeIssues(files: uploadFiles, minimum: options.minLongEdge) } else if options.minLongEdge > 0, let w = exif["ImageWidth"].flatMap({ Int($0) }), let h = exif["ImageHeight"].flatMap({ Int($0) }), max(w, h) < options.minLongEdge { issues.append(PreflightIssue(.error, "Bild zu klein: \(max(w, h)) px lange Kante (mindestens \(options.minLongEdge) px)")) } return issues.sorted { ($0.severity, $1.message) > ($1.severity, $0.message) } } /// "{city}", "{date}" … left in a text static func unresolvedVariables(in text: String) -> [String] { matches(#"\{[A-Za-z][A-Za-z0-9_]*\}"#, in: text) } /// ".w10." / "\h7\" – a code shape (letters + digits) between two delimiters static func unresolvedDelimiterCodes(in text: String, delimiter: Character) -> [String] { let d = NSRegularExpression.escapedPattern(for: String(delimiter)) return matches(d + #"[A-Za-z]{1,5}\d{1,3}(#\d+)?"# + d, in: text) } /// Words like "w10" that are codes of the enabled teams and were not expanded (typed without a space at the end). static func bareCodes(in text: String, codes: CodeReplacements) -> [String] { matches(#"(? [Date] { let f = DateFormatter() f.locale = Locale(identifier: "de_DE") f.dateFormat = "dd.MM.yyyy" return matches(#"\b\d{2}\.\d{2}\.\d{4}\b"#, in: text).compactMap { f.date(from: $0) } } static func matches(_ pattern: String, in text: String) -> [String] { guard let re = try? NSRegularExpression(pattern: pattern) else { return [] } let ns = text as NSString return re.matches(in: text, range: NSRange(location: 0, length: ns.length)).map { ns.substring(with: $0.range) } } }