// SPDX-FileCopyrightText: 2026 Brent Daignault
// SPDX-License-Identifier: GPL-3.0-or-later

import CoreGraphics
import Foundation

/// Portrait pages map one-to-one onto physical pages, in the same order the
/// content is naturally produced (cover, committee, callers, members, new
/// dancers, schedule).  That means physical page order already matches
/// logical page order, so Core Graphics' streaming PDF writer can be driven
/// directly: open a page, draw, close it, move on — no buffering needed.
enum PortraitRenderer {
    static func render(document: RosterDocument, map: PageMap, to outputPath: String) {
        let layout = Layout.portrait
        let url = URL(fileURLWithPath: outputPath) as CFURL
        var mediaBox = CGRect(x: 0, y: 0, width: layout.pageW, height: layout.pageH)

        guard let ctx = CGContext(url, mediaBox: &mediaBox, nil) else {
            FileHandle.standardError.write(
                "Failed to create PDF context for \(outputPath)\n".data(using: .utf8)!)
            return
        }

        for lp in 1...map.totalPageCount {
            ctx.beginPDFPage(nil)
            document.draw(logicalPage: lp, map: map, layout: layout, into: ctx)
            ctx.endPDFPage()
        }
        ctx.closePDF()
    }
}
