#!/usr/bin/env python3
"""Demo 1: kendi küçük motorumuz ne kadar hızlı "düşünüyor"? (CPU, tek çekirdek, Python)

Ölçülenler (ham kayıt: hiz.json):
 1) perft: başlangıçtan 1..4 yarım hamle derinlikte kaç farklı hamle dizisi var (ağacın büyümesi)
 2) aynı derinlikte düz minimax (budamasız) vs alfa-beta: kaç pozisyona bakıldı (sessizlik araması kapalı, adil karşılaştırma)
 3) tam motor (alfa-beta + sıralama + sessizlik araması) 3 pozisyonda, sabit derinliklerde: düğüm, süre, düğüm/sn
 4) arama ağacı kaydı (görselleştirme için): taktik bir pozisyonda derinlik 3, ilk 2 kat kaydedilir
"""
import json, os, platform, sys, time
import chess
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import motor as M

H = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(H, 'hiz.json')
G2 = ('1.e4 e5 2.Nf3 Nc6 3.Bb5 a6 4.Ba4 Nf6 5.O-O Be7 6.Re1 b5 7.Bb3 d6 8.c3 O-O 9.h3 h6 10.d4 Re8 11.Nbd2 Bf8 '
      '12.Nf1 Bd7 13.Ng3 Na5 14.Bc2 c5 15.b3 Nc6 16.d5 Ne7 17.Be3 Ng6 18.Qd2 Nh7 19.a4 Nh4 20.Nxh4 Qxh4 21.Qe2 Qd8 '
      '22.b4 Qc7 23.Rec1 c4 24.Ra3 Rec8 25.Rca1 Qd8 26.f4 Nf6 27.fxe5 dxe5 28.Qf1 Ne8 29.Qf2 Nd6 30.Bb6 Qe8 31.R3a2 Be7 '
      '32.Bc5 Bf8 33.Nf5 Bxf5 34.exf5 f6 35.Bxd6 Bxd6')


def board_after(sans):
    b = chess.Board()
    for tok in sans.split():
        if tok[0].isdigit():
            tok = tok.split('.')[-1]
            if not tok:
                continue
        b.push_san(tok)
    return b


def perft(b, d):
    if d == 0:
        return 1
    n = 0
    for m in b.legal_moves:
        b.push(m); n += perft(b, d - 1); b.pop()
    return n


class Sayac:
    def __init__(self):
        self.n = 0

    def minimax(self, b, d):
        self.n += 1
        if d == 0 or b.is_game_over():
            return (1 if b.turn else -1) * M.evaluate(b)
        best = -10 ** 9
        for m in b.legal_moves:
            b.push(m); best = max(best, -self.minimax(b, d - 1)); b.pop()
        return best

    def alphabeta(self, b, d, a, be):
        self.n += 1
        if d == 0 or b.is_game_over():
            return (1 if b.turn else -1) * M.evaluate(b)
        for m in b.legal_moves:  # sıralamasız: yalnız budamanın etkisi
            b.push(m); sc = -self.alphabeta(b, d - 1, -be, -a); b.pop()
            if sc >= be:
                return sc
            a = max(a, sc)
        return a


def main():
    rec = {'ortam': {'python': sys.version.split()[0], 'python_chess': chess.__version__, 'cpu': platform.processor() or platform.machine(),
                     'not': 'tek süreç, tek çekirdek; saf Python'}, 'zaman': time.strftime('%Y-%m-%dT%H:%M:%S%z')}
    try:
        rec['ortam']['cpu'] = [l.split(':', 1)[1].strip() for l in open('/proc/cpuinfo') if l.startswith('model name')][0]
    except Exception:
        pass
    b = chess.Board()
    rec['perft'] = []
    for d in range(1, 5):
        t = time.perf_counter(); n = perft(b, d)
        rec['perft'].append({'yarim_hamle': d, 'dizi': n, 'sure_sn': round(time.perf_counter() - t, 3)}); print('perft', d, n, flush=True)
    rec['budama'] = []
    for d in (2, 3, 4):
        s1 = Sayac(); t = time.perf_counter(); s1.minimax(chess.Board(), d); t1 = time.perf_counter() - t
        s2 = Sayac(); t = time.perf_counter(); s2.alphabeta(chess.Board(), d, -10 ** 9, 10 ** 9); t2 = time.perf_counter() - t
        rec['budama'].append({'derinlik': d, 'minimax_dugum': s1.n, 'minimax_sn': round(t1, 3), 'alfabeta_dugum': s2.n, 'alfabeta_sn': round(t2, 3)})
        print('budama', d, s1.n, s2.n, flush=True)
    poz = {'baslangic': chess.Board(), 'oyun2_hamle36_oncesi': board_after(G2),
           'orta_oyun_taktik': chess.Board('r1bqkb1r/pppp1ppp/2n2n2/4p2Q/2B1P3/8/PPPP1PPP/RNB1K1NR w KQkq - 4 4')}
    rec['motor'] = []
    for ad, pb in poz.items():
        for d in range(1, 6):
            m = M.Motor(max_depth=d, time_limit=600)
            # yalnız d derinliğini ölçmek için iteratif derinleştirmenin tamamı sayılır (motorun gerçek kullanımı böyle)
            mv, info = m.search(pb)
            row = {'pozisyon': ad, 'fen': pb.fen(), 'derinlik': d, 'en_iyi': pb.san(mv), 'puan_sp': info['puan_sp_siradaki_bakisindan'],
                   'dugum': info['dugum'], 'sure_sn': info['sure_sn'], 'dugum_sn': info['dugum_sn']}
            rec['motor'].append(row); print(row, flush=True)
            json.dump(rec, open(OUT, 'w'), ensure_ascii=False, indent=1)
            if info['sure_sn'] > 120:
                break
    tot_n = sum(r['dugum'] for r in rec['motor']); tot_t = sum(r['sure_sn'] for r in rec['motor'])
    rec['ozet'] = {'toplam_dugum': tot_n, 'toplam_sn': round(tot_t, 2), 'ortalama_dugum_sn': round(tot_n / tot_t),
                   'deep_blue_surekli_dugum_sn_hsu1999': 200_000_000, 'deep_blue_mac_ortalamasi_campbell2002': 126_000_000}
    rec['ozet']['kat_200M'] = round(200_000_000 / rec['ozet']['ortalama_dugum_sn'])
    rec['ozet']['kat_126M'] = round(126_000_000 / rec['ozet']['ortalama_dugum_sn'])
    # ağaç kaydı (görselleştirme): başlangıç pozisyonu, derinlik 3, ilk 2 kat; 'budanan' = alfa-beta ile hiç bakılmayan kardeş hamle sayısı
    m = M.Motor(max_depth=3, time_limit=600, record_tree=True, tree_depth=2)
    mv, info = m.search(chess.Board())
    rec['agac'] = {'fen': chess.Board().fen(), 'derinlik': 3, 'en_iyi': chess.Board().san(mv), 'bilgi': info, 'kok': m.tree}
    json.dump(rec, open(OUT, 'w'), ensure_ascii=False, indent=1)
    print(json.dumps(rec['ozet'], ensure_ascii=False))


if __name__ == '__main__':
    main()
