package aoc2025

import println
import readInput

/*
--- Day 5: Cafeteria ---
https://adventofcode.com/2025/day/5
*/
fun main() {

    val inlineTestInput = """
3-5
10-14
16-20
12-18

1
5
8
11
17
32
"""

    fun part1(input: List<String>): Int {
        val ranges = ArrayList<LongRange>()
        var freshNum = 0
        for (i in input) {
            if (i.contains("-")) {
                val (low, high) = i.split("-").map { it.toLong() }
                ranges.add(LongRange(low, high))
            } else if (i.isNotBlank()) {
                if (ranges.any { i.toLong() in it }) freshNum++
            }
        }
        return freshNum
    }

    fun part2(input: List<String>): Long {
        val ranges = ArrayList<LongRange>()
        for (i in input) {
            if (i.contains("-")) {
                val (low, high) = i.split("-").map { it.toLong() }
                ranges.add(LongRange(low, high))
            }
        }

        val consolidated = ArrayList<LongRange>()
        ranges.sortBy { it.first }
        var lastLow = ranges[0].first
        var lastHigh = ranges[0].last
        for (r in 1..ranges.lastIndex) {
            if (ranges[r].first > lastHigh) {
                consolidated.add(LongRange(lastLow, lastHigh))
                lastLow = ranges[r].first
                lastHigh = ranges[r].last
            } else {
                lastHigh = lastHigh.coerceAtLeast(ranges[r].last)
            }
        }
        consolidated.add(LongRange(lastLow, lastHigh))
        return consolidated.sumOf { it.last - it.first + 1 }
    }

    // test if implementation meets criteria from the description, like:
    val testInput = inlineTestInput.trim().reader().readLines()
    //val testInput = readInput("aoc2025/Day05_test")
    val testInputPart1Result = part1(testInput)
    println("Part 1 Test: $testInputPart1Result")
    val testInputPart2Result = part2(testInput)
    println("Part 2 Test: $testInputPart2Result")
    check(testInputPart1Result == 3)
    check(testInputPart2Result == 14L)

    val input = readInput("aoc2025/Day05")
    part1(input).println()
    part2(input).println()
}
