File size: 5,252 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
/**
 * Lichess API client
 *
 * Docs: https://lichess.org/api
 * Token: set LICHESS_API_TOKEN in .env (optional — public endpoints work without it)
 */

const LICHESS_BASE = "https://lichess.org";

function lichessHeaders(): HeadersInit {
  const token = process.env.LICHESS_API_TOKEN;
  return {
    Accept: "application/json",
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
  };
}

// --------------------------------------------------------------------------
// Puzzle types
// --------------------------------------------------------------------------

export interface LichessPuzzleGame {
  id: string;
  perf: { key: string; name: string };
  rated: boolean;
  players: { name: string; id: string; color: string }[];
  pgn: string;
  clock: string;
}

export interface LichessPuzzleData {
  id: string;
  rating: number;
  plays: number;
  solution: string[];
  themes: string[];
}

export interface LichessPuzzleResponse {
  game: LichessPuzzleGame;
  puzzle: LichessPuzzleData;
}

// --------------------------------------------------------------------------
// getLichessPuzzle
// --------------------------------------------------------------------------

/**
 * Fetches the next Lichess puzzle (daily or personalised if token supplied).
 * Returns null on fetch/parse errors so callers can fall back gracefully.
 */
export async function getLichessPuzzle(): Promise<LichessPuzzleResponse | null> {
  try {
    const res = await fetch(`${LICHESS_BASE}/api/puzzle/next`, {
      headers: lichessHeaders(),
      next: { revalidate: 0 }, // always fresh
    });

    if (!res.ok) {
      console.error(`Lichess puzzle fetch failed: ${res.status} ${res.statusText}`);
      return null;
    }

    return (await res.json()) as LichessPuzzleResponse;
  } catch (err) {
    console.error("getLichessPuzzle error:", err);
    return null;
  }
}

// --------------------------------------------------------------------------
// getLichessDailyPuzzle
// --------------------------------------------------------------------------

/**
 * Fetches today's Lichess daily puzzle (no auth required).
 */
export async function getLichessDailyPuzzle(): Promise<LichessPuzzleResponse | null> {
  try {
    const res = await fetch(`${LICHESS_BASE}/api/puzzle/daily`, {
      headers: { Accept: "application/json" },
      next: { revalidate: 3600 }, // cache for 1 hour
    });

    if (!res.ok) {
      console.error(`Lichess daily puzzle fetch failed: ${res.status} ${res.statusText}`);
      return null;
    }

    return (await res.json()) as LichessPuzzleResponse;
  } catch (err) {
    console.error("getLichessDailyPuzzle error:", err);
    return null;
  }
}

// --------------------------------------------------------------------------
// challengeStockfish
// --------------------------------------------------------------------------

export interface StockfishChallenge {
  id: string;
  url: string;
}

/**
 * Creates a Stockfish bot challenge on Lichess.
 * Requires a valid LICHESS_API_TOKEN.
 * level: 1 (easiest) → 8 (strongest)
 */
export async function challengeStockfish(
  level: number = 4,
): Promise<StockfishChallenge | null> {
  const token = process.env.LICHESS_API_TOKEN;
  if (!token) {
    console.error("challengeStockfish: LICHESS_API_TOKEN not set");
    return null;
  }

  const clampedLevel = Math.max(1, Math.min(8, level));

  const body = new URLSearchParams({
    level: String(clampedLevel),
    clock: JSON.stringify({ limit: 300, increment: 3 }),
    color: "random",
    variant: "standard",
  });

  try {
    const res = await fetch(`${LICHESS_BASE}/api/challenge/stockfish`, {
      method: "POST",
      headers: {
        ...lichessHeaders(),
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body: body.toString(),
    });

    if (!res.ok) {
      const text = await res.text();
      console.error(`challengeStockfish failed: ${res.status} ${text}`);
      return null;
    }

    const data = (await res.json()) as { id: string };
    return {
      id: data.id,
      url: `${LICHESS_BASE}/${data.id}`,
    };
  } catch (err) {
    console.error("challengeStockfish error:", err);
    return null;
  }
}

// --------------------------------------------------------------------------
// getGameStream (NDJSON event stream)
// --------------------------------------------------------------------------

/**
 * Returns a ReadableStream of NDJSON game events for the given Lichess game ID.
 * The caller is responsible for reading and parsing lines.
 * Requires LICHESS_API_TOKEN.
 */
export async function getGameStream(gameId: string): Promise<ReadableStream<Uint8Array> | null> {
  const token = process.env.LICHESS_API_TOKEN;
  if (!token) {
    console.error("getGameStream: LICHESS_API_TOKEN not set");
    return null;
  }

  try {
    const res = await fetch(`${LICHESS_BASE}/api/board/game/stream/${gameId}`, {
      headers: {
        Authorization: `Bearer ${token}`,
        Accept: "application/x-ndjson",
      },
    });

    if (!res.ok || !res.body) {
      console.error(`getGameStream failed: ${res.status}`);
      return null;
    }

    return res.body;
  } catch (err) {
    console.error("getGameStream error:", err);
    return null;
  }
}