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

import Foundation

print("""
=========================================================
ROSTER GENERATOR (Swift)  Copyright (C) 2026  Brent Daignault
bjd@biggianthead.ca  GPLv3 License
This program comes with ABSOLUTELY NO WARRANTY.
=========================================================
""")

// ── Config ───────────────────────────────────────────────────────────────────
let cfg = ConfigLoader.load()
print("Config  : title=\(cfg.titleLines.count) line(s), subtitle=\(cfg.subtitleLines.count) line(s), "
    + "\(cfg.labelSequence == .columnOrder ? "Column Order" : "Row Order")")

// ── Read CSV ─────────────────────────────────────────────────────────────────
let allMembers: [Member]
do {
    allMembers = try CSVParser.loadMembers(from: cfg.memberCSV)
} catch {
    FileHandle.standardError.write("Cannot read \(cfg.memberCSV): \(error)\n".data(using: .utf8)!)
    exit(1)
}

// ── Categorise and sort ──────────────────────────────────────────────────────
var callers: [Member] = []
var cuers: [Member] = []
var members: [Member] = []
var newDancers: [Member] = []

for m in allMembers {
    switch m.category {
    case .caller:    callers.append(m)
    case .cuer:      cuers.append(m)
    case .member:    members.append(m)
    case .newDancer: newDancers.append(m)
    case .unknown:   break
    }
}

callers = sortedByLastFirst(callers)
cuers = sortedByLastFirst(cuers)
members = sortedByLastFirst(members)
newDancers = sortedByLastFirst(newDancers)

print("Members : \(callers.count) Caller(s), \(cuers.count) Cuer(s), "
    + "\(members.count) Member(s), \(newDancers.count) New Dancer(s)")

// ── Page maps (one per output, since rows/cols per page differ) ─────────────
let bookletMap = PageMap(layout: .booklet, memberCount: members.count,
                         newDancerCount: newDancers.count, mode: .booklet)
let portraitMap = PageMap(layout: .portrait, memberCount: members.count,
                          newDancerCount: newDancers.count, mode: .portrait)

print("Booklet : \(bookletMap.contentPageCount) content pages → padded to "
    + "\(bookletMap.totalPageCount) (\(bookletMap.totalPageCount / 4) sheets)")
print("Portrait: \(portraitMap.totalPageCount) pages")

// ── Render ───────────────────────────────────────────────────────────────────
let document = RosterDocument(cfg: cfg, callers: callers, cuers: cuers,
                              members: members, newDancers: newDancers)

BookletRenderer.render(document: document, map: bookletMap, to: cfg.bookletPDF)
PortraitRenderer.render(document: document, map: portraitMap, to: cfg.standardPDF)

print("Booklet : \(cfg.bookletPDF)  (landscape, SHORT-edge duplex, collate-fold-staple)")
print("Standard: \(cfg.standardPDF)  (portrait,  LONG-edge  duplex)")
