practicode 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/core.rs ADDED
@@ -0,0 +1,831 @@
1
+ use crate::process::{CommandSpec, run_capture, which};
2
+ use anyhow::{Context, Result, anyhow, bail};
3
+ use serde::{Deserialize, Serialize};
4
+ use std::{
5
+ collections::HashMap,
6
+ fs,
7
+ path::{Path, PathBuf},
8
+ process::Command,
9
+ time::Duration,
10
+ };
11
+
12
+ pub const LANGUAGES: &[&str] = &["python", "ts", "java", "rust"];
13
+ pub const UI_LANGUAGES: &[&str] = &["ko", "en"];
14
+ pub const THEMES: &[&str] = &["dark", "light"];
15
+ pub const AI_PROVIDERS: &[&str] = &["codex", "claude"];
16
+ pub const BANK_PATH: &str = ".practicode/problem_bank.json";
17
+ pub const STATE_PATH: &str = ".practicode/problem-state.json";
18
+ pub const PROBLEM_NOTES_PATH: &str = ".practicode/problem_notes.md";
19
+
20
+ #[derive(Clone, Debug, Serialize, Deserialize)]
21
+ pub struct Settings {
22
+ #[serde(default = "default_language")]
23
+ pub language: String,
24
+ #[serde(default = "default_ui_language")]
25
+ pub ui_language: String,
26
+ #[serde(default = "default_theme")]
27
+ pub theme: String,
28
+ #[serde(default = "default_editor")]
29
+ pub editor: String,
30
+ #[serde(default = "default_next_source")]
31
+ pub next_source: String,
32
+ #[serde(default = "default_ai_provider")]
33
+ pub ai_provider: String,
34
+ #[serde(default = "default_ai_model")]
35
+ pub ai_model: String,
36
+ #[serde(default, skip_serializing_if = "String::is_empty")]
37
+ pub ai_next_command: String,
38
+ }
39
+
40
+ impl Default for Settings {
41
+ fn default() -> Self {
42
+ Self {
43
+ language: default_language(),
44
+ ui_language: default_ui_language(),
45
+ theme: default_theme(),
46
+ editor: default_editor(),
47
+ next_source: default_next_source(),
48
+ ai_provider: default_ai_provider(),
49
+ ai_model: default_ai_model(),
50
+ ai_next_command: String::new(),
51
+ }
52
+ }
53
+ }
54
+
55
+ impl Settings {
56
+ pub fn next_ai_command(&self) -> &str {
57
+ &self.ai_next_command
58
+ }
59
+
60
+ pub fn model_arg(&self) -> Option<&str> {
61
+ let model = self.ai_model.trim();
62
+ if model.is_empty() || model == "auto" {
63
+ None
64
+ } else {
65
+ Some(model)
66
+ }
67
+ }
68
+ }
69
+
70
+ #[derive(Clone, Debug, Serialize, Deserialize)]
71
+ pub struct HistoryItem {
72
+ pub id: String,
73
+ pub status: String,
74
+ }
75
+
76
+ #[derive(Clone, Debug, Serialize, Deserialize)]
77
+ pub struct AppState {
78
+ pub current_problem: String,
79
+ #[serde(default)]
80
+ pub settings: Settings,
81
+ #[serde(default)]
82
+ pub solved: Vec<String>,
83
+ #[serde(default)]
84
+ pub history: Vec<HistoryItem>,
85
+ #[serde(default = "default_suggested_difficulty")]
86
+ pub suggested_next_difficulty: String,
87
+ }
88
+
89
+ #[derive(Clone, Debug, Serialize, Deserialize)]
90
+ pub struct Problem {
91
+ pub id: String,
92
+ pub slug: String,
93
+ pub difficulty: String,
94
+ pub topics: Vec<String>,
95
+ pub title: HashMap<String, String>,
96
+ pub statement: HashMap<String, String>,
97
+ pub input: HashMap<String, String>,
98
+ pub output: HashMap<String, String>,
99
+ pub examples: Vec<IoCase>,
100
+ pub cases: Vec<IoCase>,
101
+ pub answers: HashMap<String, String>,
102
+ }
103
+
104
+ #[derive(Clone, Debug, Serialize, Deserialize)]
105
+ pub struct IoCase {
106
+ pub input: String,
107
+ pub output: String,
108
+ }
109
+
110
+ #[derive(Clone, Debug)]
111
+ pub struct JudgeResult {
112
+ pub passed: bool,
113
+ pub passed_cases: usize,
114
+ pub total_cases: usize,
115
+ pub output: String,
116
+ }
117
+
118
+ pub fn default_language() -> String {
119
+ "python".to_string()
120
+ }
121
+
122
+ pub fn default_ui_language() -> String {
123
+ "ko".to_string()
124
+ }
125
+
126
+ pub fn default_theme() -> String {
127
+ "dark".to_string()
128
+ }
129
+
130
+ pub fn default_editor() -> String {
131
+ "vim".to_string()
132
+ }
133
+
134
+ pub fn default_next_source() -> String {
135
+ "bank".to_string()
136
+ }
137
+
138
+ pub fn default_ai_provider() -> String {
139
+ "codex".to_string()
140
+ }
141
+
142
+ pub fn default_ai_model() -> String {
143
+ "auto".to_string()
144
+ }
145
+
146
+ pub fn default_suggested_difficulty() -> String {
147
+ "easy".to_string()
148
+ }
149
+
150
+ pub fn ext_for(language: &str) -> &'static str {
151
+ match normalize_language(language).as_str() {
152
+ "python" => "py",
153
+ "ts" => "ts",
154
+ "java" => "java",
155
+ "rust" => "rs",
156
+ _ => "py",
157
+ }
158
+ }
159
+
160
+ pub fn starter_problem() -> Problem {
161
+ Problem {
162
+ id: "001-hello-world".to_string(),
163
+ slug: "hello-world".to_string(),
164
+ difficulty: "easy".to_string(),
165
+ topics: vec!["io".to_string()],
166
+ title: map2("ko", "Hello World", "en", "Hello World"),
167
+ statement: map2(
168
+ "ko",
169
+ "표준 출력으로 정확히 `Hello, World!`를 출력하세요.",
170
+ "en",
171
+ "Print exactly `Hello, World!` to stdout.",
172
+ ),
173
+ input: map2("ko", "입력은 없습니다.", "en", "No input."),
174
+ output: map2(
175
+ "ko",
176
+ "`Hello, World!` 한 줄",
177
+ "en",
178
+ "One line: `Hello, World!`",
179
+ ),
180
+ examples: vec![IoCase {
181
+ input: String::new(),
182
+ output: "Hello, World!\n".to_string(),
183
+ }],
184
+ cases: vec![IoCase {
185
+ input: String::new(),
186
+ output: "Hello, World!\n".to_string(),
187
+ }],
188
+ answers: HashMap::from([
189
+ ("python".to_string(), "print('Hello, World!')\n".to_string()),
190
+ (
191
+ "ts".to_string(),
192
+ "console.log('Hello, World!');\n".to_string(),
193
+ ),
194
+ (
195
+ "java".to_string(),
196
+ "class Solution {\n public static void main(String[] args) {\n System.out.println(\"Hello, World!\");\n }\n}\n".to_string(),
197
+ ),
198
+ (
199
+ "rust".to_string(),
200
+ "fn main() {\n println!(\"Hello, World!\");\n}\n".to_string(),
201
+ ),
202
+ ]),
203
+ }
204
+ }
205
+
206
+ pub fn map2(k1: &str, v1: &str, k2: &str, v2: &str) -> HashMap<String, String> {
207
+ HashMap::from([
208
+ (k1.to_string(), v1.to_string()),
209
+ (k2.to_string(), v2.to_string()),
210
+ ])
211
+ }
212
+
213
+ pub fn load_bank(root: &Path) -> Result<Vec<Problem>> {
214
+ let path = root.join(BANK_PATH);
215
+ if path.exists() {
216
+ let text = fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
217
+ let bank: Vec<Problem> =
218
+ serde_json::from_str(&text).with_context(|| format!("parse {}", path.display()))?;
219
+ validate_bank(&bank, &path)?;
220
+ Ok(bank)
221
+ } else {
222
+ Ok(vec![starter_problem()])
223
+ }
224
+ }
225
+
226
+ pub fn save_bank(root: &Path, bank: &[Problem]) -> Result<()> {
227
+ let path = root.join(BANK_PATH);
228
+ validate_bank(bank, &path)?;
229
+ if let Some(parent) = path.parent() {
230
+ fs::create_dir_all(parent)?;
231
+ }
232
+ fs::write(&path, serde_json::to_string_pretty(bank)? + "\n")?;
233
+ Ok(())
234
+ }
235
+
236
+ fn validate_bank(bank: &[Problem], path: &Path) -> Result<()> {
237
+ if bank.is_empty() {
238
+ bail!("{} must contain at least one problem", path.display());
239
+ }
240
+ for problem in bank {
241
+ if !is_safe_name(&problem.id) {
242
+ bail!("{} has invalid problem id {:?}", path.display(), problem.id);
243
+ }
244
+ if !is_safe_name(&problem.slug) {
245
+ bail!(
246
+ "{} has invalid slug {:?} for {}",
247
+ path.display(),
248
+ problem.slug,
249
+ problem.id
250
+ );
251
+ }
252
+ if problem.cases.is_empty() {
253
+ bail!(
254
+ "{} problem {} has no judge cases",
255
+ path.display(),
256
+ problem.id
257
+ );
258
+ }
259
+ for language in LANGUAGES {
260
+ if !problem.answers.contains_key(*language) {
261
+ bail!(
262
+ "{} problem {} missing {language} answer",
263
+ path.display(),
264
+ problem.id
265
+ );
266
+ }
267
+ }
268
+ }
269
+ Ok(())
270
+ }
271
+
272
+ fn is_safe_name(value: &str) -> bool {
273
+ !value.is_empty()
274
+ && value
275
+ .chars()
276
+ .all(|char| char.is_ascii_alphanumeric() || matches!(char, '-' | '_'))
277
+ }
278
+
279
+ pub fn load_state(root: &Path, bank: &[Problem]) -> Result<AppState> {
280
+ let path = root.join(STATE_PATH);
281
+ if !path.exists() {
282
+ return Ok(AppState {
283
+ current_problem: bank[0].id.clone(),
284
+ settings: Settings::default(),
285
+ solved: Vec::new(),
286
+ history: vec![HistoryItem {
287
+ id: bank[0].id.clone(),
288
+ status: "assigned".to_string(),
289
+ }],
290
+ suggested_next_difficulty: "easy".to_string(),
291
+ });
292
+ }
293
+
294
+ let text = fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
295
+ let mut state: AppState =
296
+ serde_json::from_str(&text).with_context(|| format!("parse {}", path.display()))?;
297
+ if !bank
298
+ .iter()
299
+ .any(|problem| problem.id == state.current_problem)
300
+ {
301
+ state.current_problem = bank[0].id.clone();
302
+ }
303
+ normalize_settings(&mut state.settings);
304
+ if state.history.is_empty() {
305
+ state.history.push(HistoryItem {
306
+ id: state.current_problem.clone(),
307
+ status: "assigned".to_string(),
308
+ });
309
+ }
310
+ Ok(state)
311
+ }
312
+
313
+ pub fn save_state(root: &Path, state: &AppState) -> Result<()> {
314
+ #[derive(Serialize)]
315
+ struct StateFile<'a> {
316
+ current_problem: &'a str,
317
+ next_number: usize,
318
+ suggested_next_difficulty: &'a str,
319
+ settings: &'a Settings,
320
+ solved: &'a [String],
321
+ history: &'a [HistoryItem],
322
+ }
323
+
324
+ let path = root.join(STATE_PATH);
325
+ if let Some(parent) = path.parent() {
326
+ fs::create_dir_all(parent)?;
327
+ }
328
+ let file = StateFile {
329
+ current_problem: &state.current_problem,
330
+ next_number: state.history.len() + 1,
331
+ suggested_next_difficulty: &state.suggested_next_difficulty,
332
+ settings: &state.settings,
333
+ solved: &state.solved,
334
+ history: &state.history,
335
+ };
336
+ fs::write(path, serde_json::to_string_pretty(&file)? + "\n")?;
337
+ Ok(())
338
+ }
339
+
340
+ pub fn normalize_settings(settings: &mut Settings) {
341
+ settings.language = normalize_language(&settings.language);
342
+ if !UI_LANGUAGES.contains(&settings.ui_language.as_str()) {
343
+ settings.ui_language = "ko".to_string();
344
+ }
345
+ if !THEMES.contains(&settings.theme.as_str()) {
346
+ settings.theme = "dark".to_string();
347
+ }
348
+ settings.next_source = normalize_next_source(&settings.next_source);
349
+ settings.ai_provider = normalize_ai_provider(&settings.ai_provider);
350
+ if settings.ai_model.trim().is_empty() {
351
+ settings.ai_model = default_ai_model();
352
+ }
353
+ }
354
+
355
+ pub fn problem_by_id<'a>(bank: &'a [Problem], problem_id: &str) -> Option<&'a Problem> {
356
+ bank.iter().find(|problem| problem.id == problem_id)
357
+ }
358
+
359
+ pub fn normalize_language(language: &str) -> String {
360
+ if LANGUAGES.contains(&language) {
361
+ language.to_string()
362
+ } else {
363
+ "python".to_string()
364
+ }
365
+ }
366
+
367
+ pub fn normalize_next_source(source: &str) -> String {
368
+ if source == "ai" {
369
+ "ai".to_string()
370
+ } else {
371
+ "bank".to_string()
372
+ }
373
+ }
374
+
375
+ pub fn normalize_ai_provider(provider: &str) -> String {
376
+ if provider == "claude" {
377
+ "claude".to_string()
378
+ } else {
379
+ "codex".to_string()
380
+ }
381
+ }
382
+
383
+ pub fn localized(map: &HashMap<String, String>, lang: &str) -> String {
384
+ map.get(lang)
385
+ .or_else(|| map.get("ko"))
386
+ .or_else(|| map.get("en"))
387
+ .or_else(|| map.values().next())
388
+ .cloned()
389
+ .unwrap_or_default()
390
+ }
391
+
392
+ pub fn template_for(language: &str) -> String {
393
+ match normalize_language(language).as_str() {
394
+ "python" => "# Read from stdin and print to stdout.\nimport sys\n\n\n".to_string(),
395
+ "ts" => "const fs = require('fs');\nconst input = fs.readFileSync(0, 'utf8');\n\n".to_string(),
396
+ "java" => "import java.io.*;\n\nclass Solution {\n public static void main(String[] args) throws Exception {\n }\n}\n".to_string(),
397
+ "rust" => "fn main() {\n}\n".to_string(),
398
+ _ => String::new(),
399
+ }
400
+ }
401
+
402
+ pub fn ensure_submission(root: &Path, problem: &Problem, settings: &Settings) -> Result<PathBuf> {
403
+ let language = normalize_language(&settings.language);
404
+ let path = root
405
+ .join("submissions")
406
+ .join(&problem.id)
407
+ .join(format!("solution.{}", ext_for(&language)));
408
+ if !path.exists() {
409
+ if let Some(parent) = path.parent() {
410
+ fs::create_dir_all(parent)?;
411
+ }
412
+ fs::write(&path, template_for(&language))?;
413
+ }
414
+ Ok(path)
415
+ }
416
+
417
+ pub fn render_problem(problem: &Problem, ui_language: &str) -> String {
418
+ let lang = if UI_LANGUAGES.contains(&ui_language) {
419
+ ui_language
420
+ } else {
421
+ "ko"
422
+ };
423
+ let examples = problem
424
+ .examples
425
+ .iter()
426
+ .enumerate()
427
+ .map(|(index, case)| {
428
+ format!(
429
+ "### Example {}\n\nInput\n\n{}\n\nOutput\n\n{}",
430
+ index + 1,
431
+ fenced_text(&case.input),
432
+ fenced_text(&case.output)
433
+ )
434
+ })
435
+ .collect::<Vec<_>>()
436
+ .join("\n\n");
437
+ let number = problem
438
+ .id
439
+ .split_once('-')
440
+ .map(|(number, _)| number)
441
+ .unwrap_or(&problem.id);
442
+ format!(
443
+ "# {number}. {}\n\nDifficulty: {}\nTopics: {}\n\n{}\n\n## Input\n\n{}\n\n## Output\n\n{}\n\n## Examples\n\n{}",
444
+ localized(&problem.title, lang),
445
+ problem.difficulty,
446
+ problem.topics.join(", "),
447
+ localized(&problem.statement, lang),
448
+ localized(&problem.input, lang),
449
+ localized(&problem.output, lang),
450
+ examples
451
+ )
452
+ }
453
+
454
+ pub fn fenced_text(value: &str) -> String {
455
+ let mut body = value.to_string();
456
+ if !body.ends_with('\n') {
457
+ body.push('\n');
458
+ }
459
+ format!("```text\n{body}```")
460
+ }
461
+
462
+ pub fn judge(root: &Path, problem: &Problem, settings: &Settings) -> JudgeResult {
463
+ if problem.cases.is_empty() {
464
+ return JudgeResult {
465
+ passed: false,
466
+ passed_cases: 0,
467
+ total_cases: 0,
468
+ output: "problem has no judge cases".to_string(),
469
+ };
470
+ }
471
+ let path = match ensure_submission(root, problem, settings) {
472
+ Ok(path) => path,
473
+ Err(error) => {
474
+ return JudgeResult {
475
+ passed: false,
476
+ passed_cases: 0,
477
+ total_cases: problem.cases.len(),
478
+ output: error.to_string(),
479
+ };
480
+ }
481
+ };
482
+ let language = normalize_language(&settings.language);
483
+ let command = match command_for(root, &path, &language) {
484
+ Ok(Some(command)) => command,
485
+ Ok(None) => {
486
+ return JudgeResult {
487
+ passed: false,
488
+ passed_cases: 0,
489
+ total_cases: problem.cases.len(),
490
+ output: format!("Missing runtime for {}", settings.language),
491
+ };
492
+ }
493
+ Err(error) => {
494
+ return JudgeResult {
495
+ passed: false,
496
+ passed_cases: 0,
497
+ total_cases: problem.cases.len(),
498
+ output: format!("compile failed\n{error}"),
499
+ };
500
+ }
501
+ };
502
+ let run_dir = root.join(".practicode/build").join(&problem.id).join("run");
503
+ if let Err(error) = fs::create_dir_all(&run_dir) {
504
+ return JudgeResult {
505
+ passed: false,
506
+ passed_cases: 0,
507
+ total_cases: problem.cases.len(),
508
+ output: error.to_string(),
509
+ };
510
+ }
511
+
512
+ let mut passed = 0;
513
+ let mut lines = Vec::new();
514
+ for (index, case) in problem.cases.iter().enumerate() {
515
+ let mut process = Command::new(&command.program);
516
+ process.args(&command.args).current_dir(&run_dir);
517
+ let run = match run_capture(&mut process, &case.input, Duration::from_secs(5)) {
518
+ Ok(run) => run,
519
+ Err(error) => {
520
+ lines.push(format!("case {}: FAIL", index + 1));
521
+ lines.push(error.to_string());
522
+ break;
523
+ }
524
+ };
525
+ let got = run.stdout.trim();
526
+ let expected = case.output.trim();
527
+ if !run.timed_out && run.code == Some(0) && got == expected {
528
+ passed += 1;
529
+ lines.push(format!("case {}: PASS", index + 1));
530
+ if !run.stderr.trim().is_empty() {
531
+ lines.push("stderr:".to_string());
532
+ lines.push(run.stderr.trim_end().to_string());
533
+ }
534
+ } else {
535
+ lines.push(format!("case {}: FAIL", index + 1));
536
+ if run.timed_out {
537
+ lines.push("timeout: 5s".to_string());
538
+ }
539
+ lines.push(format!("input: {:?}", case.input));
540
+ lines.push(format!("expected: {:?}", expected));
541
+ lines.push(format!("got: {:?}", got));
542
+ lines.push("stdout:".to_string());
543
+ lines.push(if run.stdout.trim_end().is_empty() {
544
+ "<empty>".to_string()
545
+ } else {
546
+ run.stdout.trim_end().to_string()
547
+ });
548
+ if !run.stderr.trim().is_empty() {
549
+ lines.push("stderr:".to_string());
550
+ lines.push(run.stderr.trim_end().to_string());
551
+ }
552
+ break;
553
+ }
554
+ }
555
+
556
+ JudgeResult {
557
+ passed: passed == problem.cases.len(),
558
+ passed_cases: passed,
559
+ total_cases: problem.cases.len(),
560
+ output: lines.join("\n"),
561
+ }
562
+ }
563
+
564
+ pub fn command_for(root: &Path, path: &Path, language: &str) -> Result<Option<CommandSpec>> {
565
+ match language {
566
+ "python" => Ok(which("python3")
567
+ .or_else(|| which("python"))
568
+ .map(|program| CommandSpec {
569
+ program,
570
+ args: vec![path.display().to_string()],
571
+ })),
572
+ "ts" => Ok(which("node").map(|program| CommandSpec {
573
+ program,
574
+ args: vec![
575
+ "--experimental-strip-types".to_string(),
576
+ path.display().to_string(),
577
+ ],
578
+ })),
579
+ "java" => compile_java(root, path),
580
+ "rust" => compile_rust(root, path),
581
+ _ => Ok(None),
582
+ }
583
+ }
584
+
585
+ fn compile_java(root: &Path, path: &Path) -> Result<Option<CommandSpec>> {
586
+ let Some(javac) = which("javac") else {
587
+ return Ok(None);
588
+ };
589
+ let Some(java) = which("java") else {
590
+ return Ok(None);
591
+ };
592
+ let build = root
593
+ .join(".practicode/build")
594
+ .join(path.parent().and_then(Path::file_name).unwrap_or_default())
595
+ .join("java");
596
+ fs::create_dir_all(&build)?;
597
+ let mut compile = Command::new(javac);
598
+ compile
599
+ .args([
600
+ "-d",
601
+ &build.display().to_string(),
602
+ &path.display().to_string(),
603
+ ])
604
+ .current_dir(root);
605
+ let output = run_capture(&mut compile, "", Duration::from_secs(30))?;
606
+ if output.code != Some(0) {
607
+ return Err(anyhow!(output.stderr.trim().to_string()));
608
+ }
609
+ Ok(Some(CommandSpec {
610
+ program: java,
611
+ args: vec![
612
+ "-cp".to_string(),
613
+ build.display().to_string(),
614
+ "Solution".to_string(),
615
+ ],
616
+ }))
617
+ }
618
+
619
+ fn compile_rust(root: &Path, path: &Path) -> Result<Option<CommandSpec>> {
620
+ let Some(rustc) = which("rustc") else {
621
+ return Ok(None);
622
+ };
623
+ let build = root
624
+ .join(".practicode/build")
625
+ .join(path.parent().and_then(Path::file_name).unwrap_or_default());
626
+ fs::create_dir_all(&build)?;
627
+ let exe = build.join(if cfg!(windows) {
628
+ "solution.exe"
629
+ } else {
630
+ "solution"
631
+ });
632
+ let mut compile = Command::new(rustc);
633
+ compile
634
+ .args([
635
+ path.display().to_string(),
636
+ "-o".to_string(),
637
+ exe.display().to_string(),
638
+ ])
639
+ .current_dir(root);
640
+ let output = run_capture(&mut compile, "", Duration::from_secs(30))?;
641
+ if output.code != Some(0) {
642
+ return Err(anyhow!(output.stderr.trim().to_string()));
643
+ }
644
+ Ok(Some(CommandSpec {
645
+ program: exe,
646
+ args: Vec::new(),
647
+ }))
648
+ }
649
+
650
+ pub fn give_up(root: &Path, problem: &Problem, state: &mut AppState) -> Result<String> {
651
+ let language = normalize_language(&state.settings.language);
652
+ let answer = problem
653
+ .answers
654
+ .get(&language)
655
+ .cloned()
656
+ .unwrap_or_else(|| problem.answers.values().next().cloned().unwrap_or_default());
657
+ mark_history(state, &problem.id, "gave_up");
658
+ upsert_problem_index(root, problem, "gave_up")?;
659
+ save_state(root, state)?;
660
+ Ok(answer)
661
+ }
662
+
663
+ pub fn next_problem(
664
+ root: &Path,
665
+ bank: &[Problem],
666
+ state: &mut AppState,
667
+ ) -> Result<Option<Problem>> {
668
+ let seen = state
669
+ .history
670
+ .iter()
671
+ .map(|item| item.id.as_str())
672
+ .collect::<Vec<_>>();
673
+ let preferred = &state.suggested_next_difficulty;
674
+ let problem = bank
675
+ .iter()
676
+ .find(|item| !seen.contains(&item.id.as_str()) && &item.difficulty == preferred)
677
+ .or_else(|| bank.iter().find(|item| !seen.contains(&item.id.as_str())));
678
+ let Some(problem) = problem.cloned() else {
679
+ return Ok(None);
680
+ };
681
+ state.current_problem = problem.id.clone();
682
+ mark_history(state, &problem.id, "assigned");
683
+ save_state(root, state)?;
684
+ ensure_problem_files(root, &problem)?;
685
+ upsert_problem_index(root, &problem, "assigned")?;
686
+ Ok(Some(problem))
687
+ }
688
+
689
+ pub fn previous_problem(root: &Path, bank: &[Problem], state: &mut AppState) -> Result<Problem> {
690
+ let known_ids = bank
691
+ .iter()
692
+ .map(|problem| problem.id.as_str())
693
+ .collect::<Vec<_>>();
694
+ let history = state
695
+ .history
696
+ .iter()
697
+ .filter(|item| known_ids.contains(&item.id.as_str()))
698
+ .map(|item| item.id.clone())
699
+ .collect::<Vec<_>>();
700
+ let Some(index) = history.iter().position(|id| id == &state.current_problem) else {
701
+ return problem_by_id(bank, &state.current_problem)
702
+ .cloned()
703
+ .ok_or_else(|| anyhow!("current problem missing"));
704
+ };
705
+ if index == 0 {
706
+ return problem_by_id(bank, &state.current_problem)
707
+ .cloned()
708
+ .ok_or_else(|| anyhow!("current problem missing"));
709
+ }
710
+ state.current_problem = history[index - 1].clone();
711
+ save_state(root, state)?;
712
+ problem_by_id(bank, &state.current_problem)
713
+ .cloned()
714
+ .ok_or_else(|| anyhow!("current problem missing"))
715
+ }
716
+
717
+ pub fn record_pass(root: &Path, problem: &Problem, state: &mut AppState) -> Result<()> {
718
+ if !state.solved.contains(&problem.id) {
719
+ state.solved.push(problem.id.clone());
720
+ }
721
+ mark_history(state, &problem.id, "solved");
722
+ upsert_problem_index(root, problem, "solved")?;
723
+ state.suggested_next_difficulty = if state.solved.len() >= 2 {
724
+ "medium".to_string()
725
+ } else {
726
+ "easy".to_string()
727
+ };
728
+ save_state(root, state)
729
+ }
730
+
731
+ pub fn mark_history(state: &mut AppState, problem_id: &str, status: &str) {
732
+ if let Some(item) = state.history.iter_mut().find(|item| item.id == problem_id) {
733
+ item.status = status.to_string();
734
+ } else {
735
+ state.history.push(HistoryItem {
736
+ id: problem_id.to_string(),
737
+ status: status.to_string(),
738
+ });
739
+ }
740
+ }
741
+
742
+ pub fn ensure_problem_files(root: &Path, problem: &Problem) -> Result<()> {
743
+ let problem_dir = root.join("problems").join(&problem.id);
744
+ fs::create_dir_all(&problem_dir)?;
745
+ let readme = problem_dir.join("README.md");
746
+ if readme.exists() {
747
+ return Ok(());
748
+ }
749
+ let examples = problem
750
+ .examples
751
+ .iter()
752
+ .map(|case| format!("input:\n{}output:\n{}", case.input, case.output))
753
+ .collect::<Vec<_>>()
754
+ .join("\n");
755
+ fs::write(
756
+ readme,
757
+ format!(
758
+ "# {}. {}\n\n난이도: {}\n\n{}\n\n## 입력\n\n{}\n\n## 출력\n\n{}\n\n## 예시\n\n```text\n{}\n```\n",
759
+ problem.id,
760
+ localized(&problem.title, "ko"),
761
+ problem.difficulty,
762
+ localized(&problem.statement, "ko"),
763
+ localized(&problem.input, "ko"),
764
+ localized(&problem.output, "ko"),
765
+ examples
766
+ ),
767
+ )?;
768
+ Ok(())
769
+ }
770
+
771
+ pub fn upsert_problem_index(root: &Path, problem: &Problem, status: &str) -> Result<()> {
772
+ let index = root.join("problems/INDEX.md");
773
+ if let Some(parent) = index.parent() {
774
+ fs::create_dir_all(parent)?;
775
+ }
776
+ let mut rows: HashMap<String, (String, String, String, String)> = HashMap::new();
777
+ if index.exists() {
778
+ for line in fs::read_to_string(&index)?.lines() {
779
+ let parts = line
780
+ .trim()
781
+ .trim_matches('|')
782
+ .split('|')
783
+ .map(str::trim)
784
+ .collect::<Vec<_>>();
785
+ if parts.len() == 5 && parts[0].chars().all(|c| c.is_ascii_digit()) {
786
+ rows.insert(
787
+ parts[0].to_string(),
788
+ (
789
+ parts[1].to_string(),
790
+ parts[2].to_string(),
791
+ parts[3].to_string(),
792
+ parts[4].to_string(),
793
+ ),
794
+ );
795
+ }
796
+ }
797
+ }
798
+ let number = problem
799
+ .id
800
+ .split_once('-')
801
+ .map(|(number, _)| number)
802
+ .unwrap_or(&problem.id);
803
+ rows.insert(
804
+ number.to_string(),
805
+ (
806
+ problem.slug.clone(),
807
+ problem.difficulty.clone(),
808
+ problem.topics.join(", "),
809
+ status.to_string(),
810
+ ),
811
+ );
812
+ let mut numbers = rows.keys().cloned().collect::<Vec<_>>();
813
+ numbers.sort();
814
+ let body = numbers
815
+ .into_iter()
816
+ .filter_map(|number| {
817
+ rows.get(&number)
818
+ .map(|(slug, difficulty, topics, row_status)| {
819
+ format!("| {number} | {slug} | {difficulty} | {topics} | {row_status} |")
820
+ })
821
+ })
822
+ .collect::<Vec<_>>()
823
+ .join("\n");
824
+ fs::write(
825
+ index,
826
+ format!(
827
+ "# Problem Index\n\n| # | Slug | Difficulty | Topics | Status |\n|---|------|------------|--------|--------|\n{body}\n"
828
+ ),
829
+ )?;
830
+ Ok(())
831
+ }