package be.naaturel.boardmateapi.common.models;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;

public class Game {

    private static final Pattern MOVE_PATTERN = Pattern.compile(
            "^(O-O(-O)?|([KQRBN])?([a-h])?([1-8])?x?[a-h][1-8](=[QRBN])?[+#]?)$"
    );

    private final String id;
    private final String whiteName;
    private final String blackName;
    private final int timeValue;
    private final int increment;
    private final List<String> moves;

    public Game(String whiteName, String blackName, int timeValue, int increment) {
        this(null, whiteName, blackName, timeValue, increment, new ArrayList<>());
    }

    public Game(String id, String whiteName, String blackName, int timeValue, int increment, Collection<String> moves){
        this.id = id;
        this.whiteName = whiteName;
        this.blackName = blackName;
        this.timeValue = timeValue;
        this.increment = increment;
        this.moves = new ArrayList<>(moves);
    }

    public String getId(){
        return this.id;
    }

    public String getBlackName() {
        return blackName;
    }

    public String getWhiteName() {
        return whiteName;
    }

    public int getTimeValue(){
        return this.timeValue;
    }

    public int getIncrement(){
        return this.increment;
    }

    public List<String > getMoves() {
        return new ArrayList<>(moves);
    }

    public void addMove(String m) throws IllegalArgumentException {
        validateMove(m);
        this.moves.add(m);
    }

    public String getPGN() {
        StringBuilder builder = new StringBuilder();
        int moveNumber = 1;
        int movesInTurn = 1;
        for(String m : moves){

            if(movesInTurn == 1) {
                builder.append(String.format("%d. ", moveNumber));
            }
            builder.append(String.format("%s ", m));

            if(movesInTurn == 2){
                moveNumber++;
                movesInTurn = 1;
            } else {
                movesInTurn++;
            }
        }
        return builder.toString().trim();
    }

    public static void validateMove(String move) throws IllegalArgumentException {
        if (move == null || move.isBlank()) {
            throw new IllegalArgumentException("Move cannot be empty");
        }

        if (!MOVE_PATTERN.matcher(move).matches()) {
            throw new IllegalArgumentException("Invalid PGN move: " + move);
        }
    }
}
