<?php
declare(strict_types=1);

/** Board indices: a5=0, d5=3, a1=16, d1=19. Uppercase is white. */
final class Chess
{
    public static function initial(): array
    {
        $s = ['board'=>[], 'turn'=>'w', 'halfmove'=>0, 'ply'=>0, 'history'=>[], 'last'=>null];
        // Keep empty squares explicit; the position contains exactly twenty squares.
        $s['board'] = ['k','n','b','r','p','.','.','.','.','.','.','.','.','.','.','P','R','B','N','K'];
        $s['history'][] = self::key($s);
        return $s;
    }
    public static function color(string $p): ?string { return $p==='.' ? null : (ctype_upper($p)?'w':'b'); }
    public static function opposite(string $c): string { return $c==='w'?'b':'w'; }
    public static function key(array $s): string { return implode('', $s['board']).$s['turn']; }
    public static function attacked(array $b, int $target, string $by): bool
    {
        foreach ($b as $i=>$p) {
            if (self::color($p)!==$by) continue;
            $dx=$target%4-$i%4; $dy=intdiv($target,4)-intdiv($i,4); $t=strtolower($p);
            if ($t==='p' && abs($dx)===1 && $dy===($by==='w'?-1:1)) return true;
            if ($t==='n' && abs($dx)*abs($dy)===2) return true;
            if ($t==='k' && max(abs($dx),abs($dy))===1) return true;
            $diagonal=abs($dx)===abs($dy) && $dx!==0;
            $straight=($dx===0 xor $dy===0);
            if (!(($t==='b' && $diagonal)||($t==='r' && $straight)||($t==='q' && ($diagonal||$straight)))) continue;
            $sx=$dx<=>0; $sy=$dy<=>0; $x=$i%4+$sx; $y=intdiv($i,4)+$sy;
            while ($y*4+$x!==$target) { if ($b[$y*4+$x]!=='.') continue 2; $x+=$sx; $y+=$sy; }
            return true;
        }
        return false;
    }
    public static function check(array $s, ?string $color=null): bool
    {
        $color ??= $s['turn'];
        $king=array_search($color==='w'?'K':'k',$s['board'],true);
        return $king===false || self::attacked($s['board'],$king,self::opposite($color));
    }
    public static function legal(array $s): array
    {
        $out=[]; $b=$s['board']; $c=$s['turn'];
        foreach ($b as $from=>$p) {
            if (self::color($p)!==$c) continue;
            for ($to=0;$to<20;$to++) {
                if ($to===$from || self::color($b[$to])===$c || strtolower($b[$to])==='k') continue;
                $dx=$to%4-$from%4; $dy=intdiv($to,4)-intdiv($from,4);
                if (strtolower($p)==='p') {
                    $ok=$dy===($c==='w'?-1:1) && (($dx===0 && $b[$to]==='.')||(abs($dx)===1 && $b[$to]!=='.'));
                } else {
                    $ok=self::pieceReaches($b,$from,$to);
                }
                if (!$ok) continue;
                $next=$s; $next['board'][$to]=$p; $next['board'][$from]='.';
                if (self::check($next,$c)) continue;
                if (strtolower($p)==='p' && (intdiv($to,4)===0||intdiv($to,4)===4)) {
                    foreach (['q','r','b','n'] as $promotion) $out[]=['from'=>$from,'to'=>$to,'promotion'=>$promotion];
                } else $out[]=['from'=>$from,'to'=>$to,'promotion'=>null];
            }
        }
        return $out;
    }
    private static function pieceReaches(array $b,int $from,int $to): bool
    {
        $dx=$to%4-$from%4; $dy=intdiv($to,4)-intdiv($from,4); $t=strtolower($b[$from]);
        if ($t==='n') return abs($dx)*abs($dy)===2;
        if ($t==='k') return max(abs($dx),abs($dy))===1;
        $d=abs($dx)===abs($dy) && $dx!==0; $r=($dx===0 xor $dy===0);
        if (!(($t==='b'&&$d)||($t==='r'&&$r)||($t==='q'&&($d||$r)))) return false;
        $sx=$dx<=>0; $sy=$dy<=>0; $x=$from%4+$sx; $y=intdiv($from,4)+$sy;
        while ($y*4+$x!==$to) { if ($b[$y*4+$x]!=='.') return false; $x+=$sx; $y+=$sy; }
        return true;
    }
    public static function move(array $s,int $from,int $to,?string $promotion=null): array
    {
        $move=['from'=>$from,'to'=>$to,'promotion'=>$promotion];
        if (!in_array($move,self::legal($s),true)) throw new DomainException('That move is not legal.');
        return self::afterLegal($s,$move);
    }
    /** Apply a move already generated by legal(); external input must go through move(). */
    public static function afterLegal(array $s,array $move): array
    {
        ['from'=>$from,'to'=>$to,'promotion'=>$promotion]=$move;
        $p=$s['board'][$from];
        $s['halfmove']=strtolower($p)==='p'||$s['board'][$to]!=='.'?0:$s['halfmove']+1;
        $s['board'][$to]=$promotion ? ($s['turn']==='w'?strtoupper($promotion):$promotion):$p;
        $s['board'][$from]='.'; $s['turn']=self::opposite($s['turn']); $s['ply']++; $s['last']=$move;
        $s['history'][]=self::key($s); return $s;
    }
    public static function dead(array $s): bool
    {
        $minors=[];
        foreach ($s['board'] as $i=>$p) {
            if (in_array(strtolower($p),['.','k'],true)) continue;
            if (!in_array(strtolower($p),['b','n'],true)) return false;
            $minors[$i]=$p;
        }
        if (count($minors)<=1) return true;
        $squares=[];
        foreach ($minors as $i=>$p) { if (strtolower($p)!=='b') return false; $squares[]=($i%4+intdiv($i,4))%2; }
        return count(array_unique($squares))===1;
    }
    public static function repetitions(array $s): int { return count(array_filter($s['history'],fn($k)=>$k===self::key($s))); }
    public static function claimable(array $s): bool { return $s['halfmove']>=100 || self::repetitions($s)>=3; }
    public static function result(array $s): ?array
    {
        if (!self::legal($s)) return self::check($s)?['winner'=>self::opposite($s['turn']),'reason'=>'Checkmate']:['winner'=>null,'reason'=>'Stalemate'];
        if (self::dead($s)) return ['winner'=>null,'reason'=>'Dead position'];
        if ($s['halfmove']>=150) return ['winner'=>null,'reason'=>'75-move rule'];
        if (self::repetitions($s)>=5) return ['winner'=>null,'reason'=>'Fivefold repetition'];
        return null;
    }
}
