package ch.dissem.yaep.domain

import ch.dissem.yaep.domain.PuzzleSolution.MULTIPLE_SOLUTIONS
import ch.dissem.yaep.domain.PuzzleSolution.NO_SOLUTION
import ch.dissem.yaep.domain.PuzzleSolution.SOLVABLE
import kotlin.random.Random

fun generateGame(size: Int = 6): Game {
    // Generate a random puzzle instance.
    val classes = ItemClass.randomClasses(size)

    val grid: List<List<Item<ItemClass<*>>>> = classes.map {
        it.randomItems(size).map { item -> Item(item) }
    }

    // Build a set C of all possible clues that pertain to this puzzle instance.
    // (There are a finite and in fact quite small number of possible clues: for example
    // if there are 5 houses, there are 5 possible clues of the form "Person A lives in
    // house B", 8 possible clues of the form "Person A lives next to house B", and so on.)
    var clues = getAllClues(grid).shuffled()

    var i = 0

    // Run your solver on the reduced set of clues and count the number of possible solutions.

    // First do a binary search until the game isn't solvable anymore for the first time.
    var halvedClues = clues.take(clues.size / 2)
    while (solve(grid.toGrid(), halvedClues) == SOLVABLE) {
        clues = halvedClues
        halvedClues = clues.take(clues.size / 2)
    }
    // With the last solvable clues set, see what clues can be removed while the game is still solvable.
    // If i >= n, we are done. The set of clues is minimal.
    while (i < clues.size) {
        // Run your solver on the reduced set of clues and count the number of possible solutions.
        val temp = clues - clues[i]
        if (solve(grid.toGrid(), temp) == SOLVABLE) {
            // If there is exactly one solution, update clues and reset index.
            clues = temp
            i = 0
        } else {
            i++
        }
    }

    return Game(grid.toGrid(), clues)
}

fun Game.solve(): PuzzleSolution = solve(grid, clues)

internal fun solve(
    grid: Grid,
    clues: Collection<Clue>
): PuzzleSolution {
    // For each clue, remove any items that violate the clue.
    // If any cell has only one item left, remove that item from all other cells.
    // Repeat until no more items can be removed.
    var removedOptions: Boolean
    do {
        removedOptions = false
        try {
            clues.forEach { clue ->
                removedOptions = clue.removeForbiddenOptions(grid) || removedOptions
            }
        } catch (_: UnsolvablePuzzleException) {
            return NO_SOLUTION
        }
        grid.cleanupOptions()
    } while (removedOptions)

    // If any cell has no items left, the puzzle has no solution.
    if (grid.cells.any { cell -> cell.options.isEmpty() }) return NO_SOLUTION

    // If all cells have exactly one item left, the puzzle is solved.
    if (grid.cells.all { it.selection != null }) return SOLVABLE

    return MULTIPLE_SOLUTIONS
}

enum class PuzzleSolution {
    NO_SOLUTION,
    SOLVABLE,
    MULTIPLE_SOLUTIONS
}

fun getAllClues(rows: List<List<Item<ItemClass<*>>>>): MutableSet<Clue> {
    val clues = mutableSetOf<Clue>()
    rows.forEach { row ->
        row.forEachIndexed { i, item ->
            clues.add(PositionClue(item, i))
        }
    }

    rows.forEach { row ->
        row.forEachIndexed { j, item ->
            // Clue: Neighbours
            if (j > 0) {
                rows.map { it[j - 1] }.forEach {
                    // We don't want to give away the order with this clue,
                    // but it needs to be displayed consistently.
                    if (Random.nextBoolean()) {
                        clues.add(NeighbourClue(item, it))
                    } else {
                        clues.add(NeighbourClue(it, item))
                    }
                }
            }

            // Clue: Order
            if (j > 0) {
                rows.flatMap { it.take(j) }.forEach {
                    clues.add(OrderClue(it, item))
                }
            }

            // Clue: Triplet
            if (j > 1) {
                val lefts = rows.map { it[j - 2] }
                val middles = rows.map { it[j - 1] }

                lefts.forEach { left ->
                    middles.forEach { middle ->
                        // We don't want to give away the order with this clue,
                        // but it needs to be displayed consistently.
                        if (Random.nextBoolean()) {
                            clues.add(TripletClue(left, middle, item))
                        } else {
                            clues.add(TripletClue(item, middle, left))
                        }
                    }
                }
            }

            // Clue: Same Column
            rows.map { it[j] }.forEach {
                if (it != item) {
                    clues.add(SameColumnClue(item, it))
                }
            }
        }
    }
    return clues
}
