#!/usr/bin/env python3
"""Küçük satranç motoru (tarih-04 Deep Blue demosu): alfa-beta + malzeme/konum değerlendirmesi.

Deep Blue'nun kendisi değildir; Deep Blue'nun temel fikri olan "arayış + elle yazılmış değerlendirme"nin
çok küçük bir Python örneğidir. Öğrenme yok: tüm puanlar elle yazılmış sabitlerdir.

- negamax + alfa-beta budama, iteratif derinleştirme, zaman sınırı
- sıralama: önceki iterasyonun en iyi hamlesi önce, sonra MVV-LVA (en değerli taş, en ucuz saldıran), terfi
- yaprakta sessizlik araması (yalnız alımlar) — ufuk etkisini azaltır
- değerlendirme: malzeme (P100 N320 B330 R500 Q900) + taş-kare tabloları (basitleştirilmiş, elle)
- düğüm sayacı: her ziyaret edilen pozisyon (ana + sessizlik) 1 sayılır
"""
import time
import chess

VAL = {chess.PAWN: 100, chess.KNIGHT: 320, chess.BISHOP: 330, chess.ROOK: 500, chess.QUEEN: 900, chess.KING: 0}
# Taş-kare tabloları beyaz bakışından, a8..h8 ilk satır (okunabilirlik için), sonra a1'e çevrilir.
_PST = {
    chess.PAWN: [0, 0, 0, 0, 0, 0, 0, 0,
                 50, 50, 50, 50, 50, 50, 50, 50,
                 10, 10, 20, 30, 30, 20, 10, 10,
                 5, 5, 10, 25, 25, 10, 5, 5,
                 0, 0, 0, 20, 20, 0, 0, 0,
                 5, -5, -10, 0, 0, -10, -5, 5,
                 5, 10, 10, -20, -20, 10, 10, 5,
                 0, 0, 0, 0, 0, 0, 0, 0],
    chess.KNIGHT: [-50, -40, -30, -30, -30, -30, -40, -50,
                   -40, -20, 0, 0, 0, 0, -20, -40,
                   -30, 0, 10, 15, 15, 10, 0, -30,
                   -30, 5, 15, 20, 20, 15, 5, -30,
                   -30, 0, 15, 20, 20, 15, 0, -30,
                   -30, 5, 10, 15, 15, 10, 5, -30,
                   -40, -20, 0, 5, 5, 0, -20, -40,
                   -50, -40, -30, -30, -30, -30, -40, -50],
    chess.BISHOP: [-20, -10, -10, -10, -10, -10, -10, -20,
                   -10, 0, 0, 0, 0, 0, 0, -10,
                   -10, 0, 5, 10, 10, 5, 0, -10,
                   -10, 5, 5, 10, 10, 5, 5, -10,
                   -10, 0, 10, 10, 10, 10, 0, -10,
                   -10, 10, 10, 10, 10, 10, 10, -10,
                   -10, 5, 0, 0, 0, 0, 5, -10,
                   -20, -10, -10, -10, -10, -10, -10, -20],
    chess.ROOK: [0, 0, 0, 0, 0, 0, 0, 0,
                 5, 10, 10, 10, 10, 10, 10, 5,
                 -5, 0, 0, 0, 0, 0, 0, -5,
                 -5, 0, 0, 0, 0, 0, 0, -5,
                 -5, 0, 0, 0, 0, 0, 0, -5,
                 -5, 0, 0, 0, 0, 0, 0, -5,
                 -5, 0, 0, 0, 0, 0, 0, -5,
                 0, 0, 0, 5, 5, 0, 0, 0],
    chess.QUEEN: [-20, -10, -10, -5, -5, -10, -10, -20,
                  -10, 0, 0, 0, 0, 0, 0, -10,
                  -10, 0, 5, 5, 5, 5, 0, -10,
                  -5, 0, 5, 5, 5, 5, 0, -5,
                  0, 0, 5, 5, 5, 5, 0, -5,
                  -10, 5, 5, 5, 5, 5, 0, -10,
                  -10, 0, 5, 0, 0, 0, 0, -10,
                  -20, -10, -10, -5, -5, -10, -10, -20],
    chess.KING: [-30, -40, -40, -50, -50, -40, -40, -30,
                 -30, -40, -40, -50, -50, -40, -40, -30,
                 -30, -40, -40, -50, -50, -40, -40, -30,
                 -30, -40, -40, -50, -50, -40, -40, -30,
                 -20, -30, -30, -40, -40, -30, -30, -20,
                 -10, -20, -20, -20, -20, -20, -20, -10,
                 20, 20, 0, 0, 0, 0, 20, 20,
                 20, 30, 10, 0, 0, 10, 30, 20],
}
PST = {p: [t[(7 - chess.square_rank(sq)) * 8 + chess.square_file(sq)] for sq in chess.SQUARES] for p, t in _PST.items()}
MATE = 100000


def evaluate(b: chess.Board) -> int:
    """Beyaz bakışından santipiyon puanı (elle yazılmış; öğrenme yok)."""
    s = 0
    for sq, pc in b.piece_map().items():
        if pc.color == chess.WHITE:
            s += VAL[pc.piece_type] + PST[pc.piece_type][sq]
        else:
            s -= VAL[pc.piece_type] + PST[pc.piece_type][chess.square_mirror(sq)]
    return s


class Motor:
    def __init__(self, max_depth=4, time_limit=2.0, record_tree=False, tree_depth=2):
        self.max_depth, self.time_limit = max_depth, time_limit
        self.nodes = 0
        self.record_tree, self.tree_depth = record_tree, tree_depth
        self.tree = None

    def _order(self, b, moves, best=None):
        def key(m):
            if m == best:
                return -10 ** 6
            k = 0
            if b.is_capture(m):
                vic = b.piece_at(m.to_square)
                v = VAL[vic.piece_type] if vic else 100  # geçerken alma
                k -= 10 * v - VAL[b.piece_at(m.from_square).piece_type] // 10
            if m.promotion:
                k -= 8000
            return k
        return sorted(moves, key=key)

    def _side(self, b):
        return 1 if b.turn == chess.WHITE else -1

    def quiesce(self, b, alpha, beta):
        self.nodes += 1
        stand = self._side(b) * evaluate(b)
        if stand >= beta:
            return beta
        alpha = max(alpha, stand)
        for m in self._order(b, [m for m in b.legal_moves if b.is_capture(m)]):
            b.push(m)
            sc = -self.quiesce(b, -beta, -alpha)
            b.pop()
            if sc >= beta:
                return beta
            alpha = max(alpha, sc)
        return alpha

    def negamax(self, b, depth, alpha, beta, ply, node=None):
        if time.perf_counter() > self.deadline:
            raise TimeoutError
        if b.is_checkmate():
            self.nodes += 1
            return -MATE + ply
        if b.is_stalemate() or b.is_insufficient_material() or b.can_claim_fifty_moves() or b.is_repetition(3):
            self.nodes += 1
            return 0
        if depth == 0:
            return self.quiesce(b, alpha, beta)
        self.nodes += 1
        best = -MATE * 2
        moves = self._order(b, list(b.legal_moves), self.pv.get(b.fen()) if ply == 0 else None)
        for i, m in enumerate(moves):
            child = None
            if node is not None and ply < self.tree_depth:
                child = {'hamle': b.san(m), 'cocuk': []}
                node['cocuk'].append(child)
            b.push(m)
            sc = -self.negamax(b, depth - 1, -beta, -alpha, ply + 1, child)
            b.pop()
            if child is not None:
                child['puan_beyaz'] = sc * (1 if b.turn == chess.WHITE else -1)
            if sc > best:
                best = sc
                if ply == 0:
                    self.best_move = m
            if sc > alpha:
                alpha = sc
            if alpha >= beta:
                if node is not None and ply < self.tree_depth:
                    node['budanan'] = len(moves) - i - 1
                break
        return best

    def search(self, b: chess.Board):
        """İteratif derinleştirme. Döner: (hamle, bilgi dict)."""
        b = b.copy()  # zaman dolunca yarım kalan push'lar asıl tahtayı bozmasın
        self.nodes = 0
        self.pv = {}
        t0 = time.perf_counter()
        self.deadline = t0 + self.time_limit
        done_move, done_score, done_depth, per_depth = None, None, 0, []
        for d in range(1, self.max_depth + 1):
            self.best_move = None
            root = {'hamle': 'kök', 'cocuk': []} if self.record_tree else None
            n0 = self.nodes
            try:
                sc = self.negamax(b, d, -MATE * 2, MATE * 2, 0, root)
            except TimeoutError:
                break
            done_move, done_score, done_depth = self.best_move, sc, d
            self.pv[b.fen()] = self.best_move
            per_depth.append({'derinlik': d, 'dugum': self.nodes - n0, 'sure_sn': round(time.perf_counter() - t0, 4),
                              'en_iyi': b.san(self.best_move), 'puan_sp': sc})
            if root is not None:
                self.tree = root
            if abs(sc) > MATE - 100:
                break
        if done_move is None:  # derinlik 1 bile bitmediyse ilk yasal hamle (olmadı; kayıt için)
            done_move = next(iter(b.legal_moves))
        el = time.perf_counter() - t0
        return done_move, {'derinlik': done_depth, 'puan_sp_siradaki_bakisindan': done_score, 'dugum': self.nodes,
                           'sure_sn': round(el, 4), 'dugum_sn': round(self.nodes / el) if el > 0 else None,
                           'derinlik_adimlari': per_depth}
