selfware 0.2.2

Your personal AI workshop — software you own, software that lasts
Documentation
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
#![allow(dead_code, unused_imports, unused_variables)]
//! Template engine for scaffolding new projects from embedded templates.
//!
//! Provides compile-time embedded templates for Rust, Python, and Node.js/TypeScript
//! projects, with `{{placeholder}}` variable substitution and optional CI workflow
//! generation.
//!
//! This module is critical for weaker models (4B-9B) that struggle to generate correct
//! project scaffolding from scratch. The templates give the agent a correct starting
//! point so it only needs to fill in the blanks.
//!
//! # Usage
//!
//! ```ignore
//! use selfware::templates::{TemplateEngine, ScaffoldOptions};
//! use std::path::Path;
//!
//! let engine = TemplateEngine::new();
//! let opts = ScaffoldOptions {
//!     description: "A REST API service".into(),
//!     framework: Some("axum".into()),
//!     with_ci: true,
//!     with_tests: true,
//!     qa_profile: "standard".into(),
//! };
//! let files = engine.scaffold_project("rust", "my-api", Path::new("./my-api"), &opts)?;
//! ```

use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use crate::interview::InterviewContext;

// ---------------------------------------------------------------------------
// Embedded templates (compile-time via include_str!)
// ---------------------------------------------------------------------------

const RUST_CARGO_TOML: &str = include_str!("../templates/rust/Cargo.toml.template");
const PYTHON_PYPROJECT_TOML: &str = include_str!("../templates/python/pyproject.toml");
const NODEJS_PACKAGE_JSON: &str = include_str!("../templates/nodejs/package.json");
const NODEJS_TSCONFIG_JSON: &str = include_str!("../templates/nodejs/tsconfig.json");
const NODEJS_ESLINT_CONFIG: &str = include_str!("../templates/nodejs/eslint.config.mjs");
const NODEJS_PRETTIERRC: &str = include_str!("../templates/nodejs/.prettierrc");
const NODEJS_VITEST_CONFIG: &str = include_str!("../templates/nodejs/vitest.config.ts");

const WORKFLOW_RUST_QA: &str = include_str!("../templates/workflows/rust-qa.yml");
const WORKFLOW_PYTHON_QA: &str = include_str!("../templates/workflows/python-qa.yml");
const WORKFLOW_NODEJS_QA: &str = include_str!("../templates/workflows/nodejs-qa.yml");
const WORKFLOW_ORCHESTRATOR: &str =
    include_str!("../templates/workflows/selfware-qa-orchestrator.yml");

const QA_SCHEMA_YAML: &str = include_str!("../selfware-qa-schema.yaml");

// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------

/// Options controlling how a project is scaffolded.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScaffoldOptions {
    /// Short description of the project.
    pub description: String,
    /// Framework / library to wire into the scaffold (e.g. "axum", "FastAPI").
    pub framework: Option<String>,
    /// Include a CI workflow in `.github/workflows/`.
    pub with_ci: bool,
    /// Include test directories and test configuration.
    pub with_tests: bool,
    /// QA profile to use: "standard", "strict", or "minimal".
    pub qa_profile: String,
}

impl Default for ScaffoldOptions {
    fn default() -> Self {
        Self {
            description: String::new(),
            framework: None,
            with_ci: true,
            with_tests: true,
            qa_profile: "standard".into(),
        }
    }
}

/// Metadata about an available template.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemplateInfo {
    /// Language identifier (e.g. "rust", "python", "nodejs").
    pub language: String,
    /// Human-readable description.
    pub description: String,
    /// Files that will be created by this template.
    pub files: Vec<String>,
}

// ---------------------------------------------------------------------------
// QA schema types (parsed from selfware-qa-schema.yaml)
// ---------------------------------------------------------------------------

/// Top-level QA schema configuration parsed from YAML.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QaSchemaConfig {
    pub qa_profile: QaSchemaProfile,
}

/// A single QA profile from the schema.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QaSchemaProfile {
    pub name: String,
    #[serde(default)]
    pub description: String,
    #[serde(default)]
    pub version: String,
    #[serde(default)]
    pub extends: Option<String>,
    #[serde(default)]
    pub stages: Vec<QaSchemaStage>,
    #[serde(default)]
    pub quality_gates: Vec<QaSchemaGate>,
    #[serde(default)]
    pub scoring: Option<QaSchemaScoring>,
    #[serde(default)]
    pub coverage: Option<QaSchemaCoverage>,
    #[serde(default)]
    pub feedback_loops: Option<QaSchemaFeedbackLoops>,
    #[serde(default)]
    pub language_overrides: Option<HashMap<String, serde_yaml::Value>>,
}

/// A QA pipeline stage definition from the schema.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QaSchemaStage {
    pub name: String,
    #[serde(default)]
    pub description: String,
    #[serde(default = "default_true")]
    pub required: bool,
    #[serde(default)]
    pub fail_fast: bool,
    #[serde(default = "default_timeout")]
    pub timeout_seconds: u64,
    #[serde(default)]
    pub coverage_threshold: Option<u64>,
    #[serde(default)]
    pub severity_threshold: Option<String>,
    #[serde(default)]
    pub tools: HashMap<String, Vec<QaSchemaTool>>,
}

fn default_true() -> bool {
    true
}
fn default_timeout() -> u64 {
    60
}

/// A tool command within a QA stage.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QaSchemaTool {
    pub command: String,
    #[serde(default)]
    pub env: HashMap<String, String>,
}

/// Quality gate definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QaSchemaGate {
    pub stage: String,
    #[serde(default)]
    pub fail_on_error: bool,
    #[serde(default)]
    pub max_warnings: Option<u64>,
    #[serde(default)]
    pub min_coverage: Option<u64>,
    #[serde(default)]
    pub severity_threshold: Option<String>,
    #[serde(default)]
    pub description: String,
}

/// Scoring weights and grade thresholds.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QaSchemaScoring {
    #[serde(default)]
    pub weights: HashMap<String, f64>,
    #[serde(default)]
    pub grade_thresholds: HashMap<String, u64>,
}

/// Coverage configuration from the schema.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QaSchemaCoverage {
    #[serde(default)]
    pub min_overall: u64,
    #[serde(default)]
    pub min_per_file: u64,
    #[serde(default)]
    pub exclude_patterns: Vec<String>,
}

/// Feedback loop configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QaSchemaFeedbackLoops {
    #[serde(default)]
    pub auto_fix: Option<serde_yaml::Value>,
    #[serde(default)]
    pub retry_with_context: Option<serde_yaml::Value>,
    #[serde(default)]
    pub escalation: Option<serde_yaml::Value>,
}

// ---------------------------------------------------------------------------
// TemplateEngine
// ---------------------------------------------------------------------------

/// Engine for scaffolding new projects from embedded or runtime-override templates.
pub struct TemplateEngine {
    /// Optional directory for user-level template overrides (e.g. `~/.selfware/templates/`).
    override_dir: Option<PathBuf>,
}

impl Default for TemplateEngine {
    fn default() -> Self {
        Self::new()
    }
}

impl TemplateEngine {
    /// Create a new engine. If `~/.selfware/templates/` exists, it will be used
    /// as a runtime override source.
    pub fn new() -> Self {
        let override_dir = dirs::home_dir()
            .map(|h| h.join(".selfware").join("templates"))
            .filter(|p| p.is_dir());
        Self { override_dir }
    }

    /// Create an engine with a specific override directory (useful for testing).
    pub fn with_override_dir(dir: Option<PathBuf>) -> Self {
        Self {
            override_dir: dir.filter(|p| p.is_dir()),
        }
    }

    // -----------------------------------------------------------------------
    // Template rendering
    // -----------------------------------------------------------------------

    /// Replace all `{{placeholder}}` occurrences in `template` with values from `vars`.
    /// Unrecognized placeholders are left as-is.
    pub fn render_template(template: &str, vars: &HashMap<String, String>) -> String {
        let mut result = template.to_string();
        for (key, value) in vars {
            let placeholder = format!("{{{{{}}}}}", key);
            result = result.replace(&placeholder, value);
        }
        result
    }

    // -----------------------------------------------------------------------
    // Template listing
    // -----------------------------------------------------------------------

    /// List all available templates with descriptions.
    pub fn available_templates() -> Vec<TemplateInfo> {
        vec![
            TemplateInfo {
                language: "rust".into(),
                description: "Rust project with Cargo.toml, src/main.rs, src/lib.rs, tests/".into(),
                files: vec![
                    "Cargo.toml".into(),
                    "src/main.rs".into(),
                    "src/lib.rs".into(),
                    "tests/integration_test.rs".into(),
                ],
            },
            TemplateInfo {
                language: "python".into(),
                description: "Python project with pyproject.toml, src/<module>/__init__.py, tests/"
                    .into(),
                files: vec![
                    "pyproject.toml".into(),
                    "src/<module>/__init__.py".into(),
                    "src/<module>/cli.py".into(),
                    "tests/__init__.py".into(),
                    "tests/test_main.py".into(),
                ],
            },
            TemplateInfo {
                language: "nodejs".into(),
                description:
                    "Node.js/TypeScript project with package.json, tsconfig, eslint, vitest".into(),
                files: vec![
                    "package.json".into(),
                    "tsconfig.json".into(),
                    "eslint.config.mjs".into(),
                    ".prettierrc".into(),
                    "vitest.config.ts".into(),
                    "src/index.ts".into(),
                    "tests/index.test.ts".into(),
                ],
            },
        ]
    }

    // -----------------------------------------------------------------------
    // Template loading (embedded or runtime override)
    // -----------------------------------------------------------------------

    /// Load a template file, preferring a runtime override if present.
    fn load_template(&self, relative_path: &str, embedded: &str) -> String {
        if let Some(ref dir) = self.override_dir {
            let override_path = dir.join(relative_path);
            if override_path.is_file() {
                if let Ok(content) = std::fs::read_to_string(&override_path) {
                    return content;
                }
            }
        }
        embedded.to_string()
    }

    // -----------------------------------------------------------------------
    // Project scaffolding
    // -----------------------------------------------------------------------

    /// Scaffold a new project from templates.
    ///
    /// Returns the list of files created (relative to `project_dir`).
    pub fn scaffold_project(
        &self,
        language: &str,
        project_name: &str,
        project_dir: &Path,
        options: &ScaffoldOptions,
    ) -> Result<Vec<String>> {
        let lang = language.to_lowercase();
        match lang.as_str() {
            "rust" => self.scaffold_rust(project_name, project_dir, options),
            "python" => self.scaffold_python(project_name, project_dir, options),
            "nodejs" | "node" | "typescript" | "node.js" | "ts" => {
                self.scaffold_nodejs(project_name, project_dir, options)
            }
            other => bail!(
                "Unsupported language '{}'. Supported: rust, python, nodejs",
                other
            ),
        }
    }

    /// Build the standard variable map for template rendering.
    fn build_vars(&self, project_name: &str, options: &ScaffoldOptions) -> HashMap<String, String> {
        let module_name = project_name.replace('-', "_");
        let mut vars = HashMap::new();
        vars.insert("project_name".into(), project_name.into());
        vars.insert("project_description".into(), options.description.clone());
        vars.insert("module_name".into(), module_name);
        vars.insert("repository_url".into(), String::new());
        vars.insert("project_url".into(), String::new());
        vars.insert("docs_url".into(), String::new());
        vars.insert("keywords".into(), String::new());
        vars.insert("categories".into(), String::new());
        vars
    }

    /// Write a file and record its relative path.
    fn write_file(
        project_dir: &Path,
        relative: &str,
        content: &str,
        created: &mut Vec<String>,
    ) -> Result<()> {
        let full = project_dir.join(relative);
        if let Some(parent) = full.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("creating directory {}", parent.display()))?;
        }
        std::fs::write(&full, content).with_context(|| format!("writing {}", full.display()))?;
        created.push(relative.to_string());
        Ok(())
    }

    // -- Rust ---------------------------------------------------------------

    fn scaffold_rust(
        &self,
        project_name: &str,
        project_dir: &Path,
        options: &ScaffoldOptions,
    ) -> Result<Vec<String>> {
        let vars = self.build_vars(project_name, options);
        let mut created = Vec::new();

        // Cargo.toml
        let cargo_tmpl = self.load_template("rust/Cargo.toml", RUST_CARGO_TOML);
        let cargo_content = Self::render_template(&cargo_tmpl, &vars);
        Self::write_file(project_dir, "Cargo.toml", &cargo_content, &mut created)?;

        // src/main.rs
        let main_rs = format!(
            r#"use anyhow::Result;

fn main() -> Result<()> {{
    println!("Hello from {}!");
    Ok(())
}}
"#,
            project_name
        );
        Self::write_file(project_dir, "src/main.rs", &main_rs, &mut created)?;

        // src/lib.rs
        let lib_rs = format!(
            r#"//! {} - {}

pub fn greet() -> &'static str {{
    "Hello from {}!"
}}
"#,
            project_name, options.description, project_name
        );
        Self::write_file(project_dir, "src/lib.rs", &lib_rs, &mut created)?;

        // tests/
        if options.with_tests {
            let test_rs = format!(
                r#"use {}::greet;

#[test]
fn test_greet() {{
    assert!(greet().contains("{}"));
}}
"#,
                project_name.replace('-', "_"),
                project_name,
            );
            Self::write_file(
                project_dir,
                "tests/integration_test.rs",
                &test_rs,
                &mut created,
            )?;
        }

        // CI workflow
        if options.with_ci {
            let wf = self.load_template("workflows/rust-qa.yml", WORKFLOW_RUST_QA);
            Self::write_file(
                project_dir,
                ".github/workflows/rust-qa.yml",
                &wf,
                &mut created,
            )?;
        }

        Ok(created)
    }

    // -- Python -------------------------------------------------------------

    fn scaffold_python(
        &self,
        project_name: &str,
        project_dir: &Path,
        options: &ScaffoldOptions,
    ) -> Result<Vec<String>> {
        let vars = self.build_vars(project_name, options);
        let module_name = project_name.replace('-', "_");
        let mut created = Vec::new();

        // pyproject.toml
        let pyproject_tmpl = self.load_template("python/pyproject.toml", PYTHON_PYPROJECT_TOML);
        let pyproject_content = Self::render_template(&pyproject_tmpl, &vars);
        Self::write_file(
            project_dir,
            "pyproject.toml",
            &pyproject_content,
            &mut created,
        )?;

        // src/<module>/__init__.py
        let init_py = format!(
            r#""""{} - {}""""

__version__ = "0.1.0"


def main() -> None:
    """Entry point."""
    print("Hello from {}!")
"#,
            module_name, options.description, project_name
        );
        Self::write_file(
            project_dir,
            &format!("src/{}/__init__.py", module_name),
            &init_py,
            &mut created,
        )?;

        // src/<module>/cli.py
        let cli_py = format!(
            r#"""Command-line interface for {}.""

import argparse

from . import main


def cli() -> None:
    """Parse arguments and run."""
    parser = argparse.ArgumentParser(description="{}")
    _ = parser.parse_args()
    main()


if __name__ == "__main__":
    cli()
"#,
            project_name, options.description
        );
        Self::write_file(
            project_dir,
            &format!("src/{}/cli.py", module_name),
            &cli_py,
            &mut created,
        )?;

        // tests/
        if options.with_tests {
            Self::write_file(project_dir, "tests/__init__.py", "", &mut created)?;

            let test_py = format!(
                r#"""Tests for {}.""

from {} import main


def test_main(capsys):
    """Test that main runs without error."""
    main()
    captured = capsys.readouterr()
    assert "{}" in captured.out
"#,
                project_name, module_name, project_name
            );
            Self::write_file(project_dir, "tests/test_main.py", &test_py, &mut created)?;
        }

        // CI workflow
        if options.with_ci {
            let wf = self.load_template("workflows/python-qa.yml", WORKFLOW_PYTHON_QA);
            Self::write_file(
                project_dir,
                ".github/workflows/python-qa.yml",
                &wf,
                &mut created,
            )?;
        }

        Ok(created)
    }

    // -- Node.js / TypeScript -----------------------------------------------

    fn scaffold_nodejs(
        &self,
        project_name: &str,
        project_dir: &Path,
        options: &ScaffoldOptions,
    ) -> Result<Vec<String>> {
        let vars = self.build_vars(project_name, options);
        let mut created = Vec::new();

        // package.json
        let pkg_tmpl = self.load_template("nodejs/package.json", NODEJS_PACKAGE_JSON);
        let pkg_content = Self::render_template(&pkg_tmpl, &vars);
        Self::write_file(project_dir, "package.json", &pkg_content, &mut created)?;

        // tsconfig.json
        let tsconfig = self.load_template("nodejs/tsconfig.json", NODEJS_TSCONFIG_JSON);
        Self::write_file(project_dir, "tsconfig.json", &tsconfig, &mut created)?;

        // eslint.config.mjs
        let eslint = self.load_template("nodejs/eslint.config.mjs", NODEJS_ESLINT_CONFIG);
        Self::write_file(project_dir, "eslint.config.mjs", &eslint, &mut created)?;

        // .prettierrc
        let prettier = self.load_template("nodejs/.prettierrc", NODEJS_PRETTIERRC);
        Self::write_file(project_dir, ".prettierrc", &prettier, &mut created)?;

        // vitest.config.ts
        let vitest = self.load_template("nodejs/vitest.config.ts", NODEJS_VITEST_CONFIG);
        Self::write_file(project_dir, "vitest.config.ts", &vitest, &mut created)?;

        // src/index.ts
        let index_ts = format!(
            r#"/**
 * {} - {}
 */

export function greet(): string {{
  return "Hello from {}!";
}}

console.log(greet());
"#,
            project_name, options.description, project_name
        );
        Self::write_file(project_dir, "src/index.ts", &index_ts, &mut created)?;

        // tests/
        if options.with_tests {
            let test_ts = format!(
                r#"import {{ describe, it, expect }} from "vitest";
import {{ greet }} from "../src/index";

describe("{}", () => {{
  it("should greet correctly", () => {{
    const result = greet();
    expect(result).toContain("{}");
  }});
}});
"#,
                project_name, project_name,
            );
            Self::write_file(project_dir, "tests/index.test.ts", &test_ts, &mut created)?;
        }

        // CI workflow
        if options.with_ci {
            let wf = self.load_template("workflows/nodejs-qa.yml", WORKFLOW_NODEJS_QA);
            Self::write_file(
                project_dir,
                ".github/workflows/nodejs-qa.yml",
                &wf,
                &mut created,
            )?;
        }

        Ok(created)
    }
}

// ---------------------------------------------------------------------------
// QA schema loading
// ---------------------------------------------------------------------------

/// Load and parse the QA schema configuration.
///
/// If `path` is `Some`, reads from that file on disk; otherwise uses the
/// embedded `selfware-qa-schema.yaml`.
///
/// The YAML file contains multiple documents (separated by `---`). This
/// function parses the first document (the standard profile) by default.
pub fn load_qa_schema(path: Option<&Path>) -> Result<QaSchemaConfig> {
    // Default to loading the "standard" profile (first document).
    load_qa_schema_profile(path, "standard")
}

/// Load a specific QA profile by name from the multi-document schema.
///
/// Iterates over all YAML documents and returns the one matching `profile_name`.
pub fn load_qa_schema_profile(path: Option<&Path>, profile_name: &str) -> Result<QaSchemaConfig> {
    let content = match path {
        Some(p) => std::fs::read_to_string(p)
            .with_context(|| format!("reading QA schema from {}", p.display()))?,
        None => QA_SCHEMA_YAML.to_string(),
    };

    for document in serde_yaml::Deserializer::from_str(&content) {
        if let Ok(config) = QaSchemaConfig::deserialize(document) {
            if config.qa_profile.name == profile_name {
                return Ok(config);
            }
        }
    }

    bail!(
        "QA profile '{}' not found in schema. Available: standard, strict, minimal",
        profile_name
    )
}

/// Convert a [`QaSchemaConfig`] into weights compatible with
/// `QaWeights` from the QA profiles module.
pub fn qa_schema_to_weights(schema: &QaSchemaConfig) -> crate::testing::qa_profiles::QaWeights {
    let defaults = crate::testing::qa_profiles::QaWeights::standard();
    let scoring = match &schema.qa_profile.scoring {
        Some(s) => &s.weights,
        None => return defaults,
    };

    // The schema uses 0.0-1.0 weights; QaWeights uses absolute points
    // that sum to ~80. We scale by 100 to keep proportions.
    let get =
        |key: &str, fallback: f64| -> f64 { scoring.get(key).copied().unwrap_or(fallback) * 100.0 };

    crate::testing::qa_profiles::QaWeights {
        syntax: get("syntax", 0.10),
        format: get("format", 0.05),
        lint: get("lint", 0.15),
        type_check: get("typecheck", 0.10),
        test: get("test", 0.30),
        security: get("security", 0.10),
    }
}

// ---------------------------------------------------------------------------
// Interview integration
// ---------------------------------------------------------------------------

/// Scaffold a project based on answers collected during an interview session.
///
/// Maps [`InterviewContext`] fields to [`ScaffoldOptions`] and invokes the
/// template engine.
pub fn scaffold_from_context(ctx: &InterviewContext, project_dir: &Path) -> Result<Vec<String>> {
    let language = ctx.language.as_deref().unwrap_or("rust").to_lowercase();

    // Normalise interview language strings to template identifiers.
    let lang_key = if language.contains("typescript") || language.contains("node") {
        "nodejs"
    } else if language.contains("python") {
        "python"
    } else if language.contains("rust") {
        "rust"
    } else {
        // Best-effort: try as-is (will fail gracefully for unsupported langs).
        &language
    };

    // Derive a project name from the output directory or task.
    let project_name = project_dir
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("my-project")
        .to_string();

    let qa_profile = match ctx.testing_preference {
        Some(crate::interview::TestingPreference::Tdd) => "strict",
        Some(crate::interview::TestingPreference::Minimal) => "minimal",
        Some(crate::interview::TestingPreference::None) => "minimal",
        _ => "standard",
    };

    let with_tests = !matches!(
        ctx.testing_preference,
        Some(crate::interview::TestingPreference::None)
    );

    let description = if ctx.task.is_empty() {
        ctx.extra_notes.first().cloned().unwrap_or_default()
    } else {
        ctx.task.clone()
    };

    let options = ScaffoldOptions {
        description,
        framework: ctx.framework.clone(),
        with_ci: true,
        with_tests,
        qa_profile: qa_profile.into(),
    };

    let engine = TemplateEngine::new();
    engine.scaffold_project(lang_key, &project_name, project_dir, &options)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use tempfile::TempDir;

    // -- Template rendering -------------------------------------------------

    #[test]
    fn test_render_template_basic() {
        let mut vars = HashMap::new();
        vars.insert("name".into(), "hello-world".into());
        vars.insert("desc".into(), "A test project".into());

        let result = TemplateEngine::render_template("name={{name}}, desc={{desc}}", &vars);
        assert_eq!(result, "name=hello-world, desc=A test project");
    }

    #[test]
    fn test_render_template_missing_placeholder_kept() {
        let vars = HashMap::new();
        let result = TemplateEngine::render_template("{{unknown}}", &vars);
        assert_eq!(result, "{{unknown}}");
    }

    #[test]
    fn test_render_template_multiple_occurrences() {
        let mut vars = HashMap::new();
        vars.insert("x".into(), "42".into());
        let result = TemplateEngine::render_template("a={{x}} b={{x}}", &vars);
        assert_eq!(result, "a=42 b=42");
    }

    #[test]
    fn test_render_template_empty_value() {
        let mut vars = HashMap::new();
        vars.insert("project_name".into(), "".into());
        let result = TemplateEngine::render_template("name={{project_name}}", &vars);
        assert_eq!(result, "name=");
    }

    #[test]
    fn test_render_template_no_placeholders() {
        let vars = HashMap::new();
        let result = TemplateEngine::render_template("plain text", &vars);
        assert_eq!(result, "plain text");
    }

    // -- Rust scaffolding ---------------------------------------------------

    #[test]
    fn test_scaffold_rust_project() {
        let dir = TempDir::new().unwrap();
        let engine = TemplateEngine::with_override_dir(None);
        let opts = ScaffoldOptions {
            description: "Test Rust project".into(),
            framework: None,
            with_ci: true,
            with_tests: true,
            qa_profile: "standard".into(),
        };

        let files = engine
            .scaffold_project("rust", "my-app", dir.path(), &opts)
            .unwrap();

        // Verify Cargo.toml was created with correct name
        let cargo_path = dir.path().join("Cargo.toml");
        assert!(cargo_path.exists(), "Cargo.toml should exist");
        let cargo_content = std::fs::read_to_string(&cargo_path).unwrap();
        assert!(
            cargo_content.contains("name = \"my-app\""),
            "Cargo.toml should contain project name"
        );
        assert!(
            cargo_content.contains("Test Rust project"),
            "Cargo.toml should contain description"
        );

        // Verify src/main.rs
        assert!(dir.path().join("src/main.rs").exists());
        let main_content = std::fs::read_to_string(dir.path().join("src/main.rs")).unwrap();
        assert!(main_content.contains("my-app"));

        // Verify src/lib.rs
        assert!(dir.path().join("src/lib.rs").exists());

        // Verify tests/
        assert!(dir.path().join("tests/integration_test.rs").exists());

        // Verify CI workflow
        assert!(dir.path().join(".github/workflows/rust-qa.yml").exists());

        // All expected files present
        assert!(files.contains(&"Cargo.toml".to_string()));
        assert!(files.contains(&"src/main.rs".to_string()));
        assert!(files.contains(&"src/lib.rs".to_string()));
        assert!(files.contains(&"tests/integration_test.rs".to_string()));
        assert!(files.contains(&".github/workflows/rust-qa.yml".to_string()));
    }

    // -- Python scaffolding -------------------------------------------------

    #[test]
    fn test_scaffold_python_project() {
        let dir = TempDir::new().unwrap();
        let engine = TemplateEngine::with_override_dir(None);
        let opts = ScaffoldOptions {
            description: "Test Python project".into(),
            framework: None,
            with_ci: true,
            with_tests: true,
            qa_profile: "standard".into(),
        };

        let files = engine
            .scaffold_project("python", "my-api", dir.path(), &opts)
            .unwrap();

        // Verify pyproject.toml
        let pyproject_path = dir.path().join("pyproject.toml");
        assert!(pyproject_path.exists(), "pyproject.toml should exist");
        let pyproject_content = std::fs::read_to_string(&pyproject_path).unwrap();
        assert!(
            pyproject_content.contains("name = \"my-api\""),
            "pyproject.toml should contain project name"
        );

        // Verify module directory
        assert!(dir.path().join("src/my_api/__init__.py").exists());
        assert!(dir.path().join("src/my_api/cli.py").exists());

        // Verify tests
        assert!(dir.path().join("tests/__init__.py").exists());
        assert!(dir.path().join("tests/test_main.py").exists());

        // Verify CI
        assert!(dir.path().join(".github/workflows/python-qa.yml").exists());

        assert!(files.contains(&"pyproject.toml".to_string()));
        assert!(files.contains(&"src/my_api/__init__.py".to_string()));
    }

    // -- Node.js scaffolding ------------------------------------------------

    #[test]
    fn test_scaffold_nodejs_project() {
        let dir = TempDir::new().unwrap();
        let engine = TemplateEngine::with_override_dir(None);
        let opts = ScaffoldOptions {
            description: "Test Node project".into(),
            framework: None,
            with_ci: true,
            with_tests: true,
            qa_profile: "standard".into(),
        };

        let files = engine
            .scaffold_project("nodejs", "my-service", dir.path(), &opts)
            .unwrap();

        // Verify all 5 config files
        assert!(dir.path().join("package.json").exists());
        assert!(dir.path().join("tsconfig.json").exists());
        assert!(dir.path().join("eslint.config.mjs").exists());
        assert!(dir.path().join(".prettierrc").exists());
        assert!(dir.path().join("vitest.config.ts").exists());

        // Verify source and test
        assert!(dir.path().join("src/index.ts").exists());
        assert!(dir.path().join("tests/index.test.ts").exists());

        // Verify package.json has correct name
        let pkg_content = std::fs::read_to_string(dir.path().join("package.json")).unwrap();
        assert!(pkg_content.contains("\"name\": \"my-service\""));

        // CI
        assert!(dir.path().join(".github/workflows/nodejs-qa.yml").exists());

        // Check all 5 config files are in the list
        assert!(files.contains(&"package.json".to_string()));
        assert!(files.contains(&"tsconfig.json".to_string()));
        assert!(files.contains(&"eslint.config.mjs".to_string()));
        assert!(files.contains(&".prettierrc".to_string()));
        assert!(files.contains(&"vitest.config.ts".to_string()));
    }

    #[test]
    fn test_scaffold_nodejs_aliases() {
        // All aliases should work
        let dir = TempDir::new().unwrap();
        let engine = TemplateEngine::with_override_dir(None);
        let opts = ScaffoldOptions::default();

        for alias in &["nodejs", "node", "typescript", "node.js", "ts"] {
            let sub = dir.path().join(alias);
            std::fs::create_dir_all(&sub).unwrap();
            let result = engine.scaffold_project(alias, "test", &sub, &opts);
            assert!(
                result.is_ok(),
                "alias '{}' should succeed: {:?}",
                alias,
                result.err()
            );
        }
    }

    // -- QA schema ----------------------------------------------------------

    #[test]
    fn test_load_qa_schema_embedded() {
        let config = load_qa_schema(None).unwrap();
        assert_eq!(config.qa_profile.name, "standard");
        assert!(!config.qa_profile.stages.is_empty());
        assert!(!config.qa_profile.quality_gates.is_empty());
    }

    #[test]
    fn test_load_qa_schema_from_disk() {
        let dir = TempDir::new().unwrap();
        let schema_path = dir.path().join("qa-schema.yaml");
        std::fs::write(&schema_path, QA_SCHEMA_YAML).unwrap();

        let config = load_qa_schema_profile(Some(&schema_path), "standard").unwrap();
        assert_eq!(config.qa_profile.name, "standard");
    }

    #[test]
    fn test_load_qa_schema_profile_standard() {
        let config = load_qa_schema_profile(None, "standard").unwrap();
        assert_eq!(config.qa_profile.name, "standard");
    }

    #[test]
    fn test_load_qa_schema_profile_strict() {
        let config = load_qa_schema_profile(None, "strict").unwrap();
        assert_eq!(config.qa_profile.name, "strict");
    }

    #[test]
    fn test_load_qa_schema_profile_minimal() {
        let config = load_qa_schema_profile(None, "minimal").unwrap();
        assert_eq!(config.qa_profile.name, "minimal");
    }

    #[test]
    fn test_load_qa_schema_profile_unknown() {
        let result = load_qa_schema_profile(None, "nonexistent");
        assert!(result.is_err());
    }

    #[test]
    fn test_qa_schema_to_weights() {
        let config = load_qa_schema(None).unwrap();
        let weights = qa_schema_to_weights(&config);
        // syntax weight = 0.10 * 100 = 10.0
        assert!((weights.syntax - 10.0).abs() < 0.01);
        // test weight = 0.30 * 100 = 30.0
        assert!((weights.test - 30.0).abs() < 0.01);
        assert!(weights.total() > 0.0);
    }

    // -- Embedded template validity -----------------------------------------

    #[test]
    fn test_embedded_rust_cargo_toml_is_valid_toml() {
        // Render with dummy vars first so placeholders don't break parsing
        let mut vars = HashMap::new();
        vars.insert("project_name".into(), "test_project".into());
        vars.insert("project_description".into(), "test".into());
        vars.insert("repository_url".into(), "".into());
        vars.insert("project_url".into(), "".into());
        vars.insert("keywords".into(), "test".into());
        vars.insert("categories".into(), "test".into());

        let rendered = TemplateEngine::render_template(RUST_CARGO_TOML, &vars);
        let parsed: Result<toml::Value, _> = toml::from_str(&rendered);
        assert!(
            parsed.is_ok(),
            "Rendered Cargo.toml should be valid TOML: {:?}",
            parsed.err()
        );
    }

    #[test]
    fn test_embedded_nodejs_package_json_is_valid_json() {
        let mut vars = HashMap::new();
        vars.insert("project_name".into(), "test-project".into());
        vars.insert("project_description".into(), "test".into());
        vars.insert("repository_url".into(), "".into());
        vars.insert("project_url".into(), "".into());
        vars.insert("keywords".into(), "test".into());

        let rendered = TemplateEngine::render_template(NODEJS_PACKAGE_JSON, &vars);
        let parsed: Result<serde_json::Value, _> = serde_json::from_str(&rendered);
        assert!(
            parsed.is_ok(),
            "Rendered package.json should be valid JSON: {:?}",
            parsed.err()
        );
    }

    #[test]
    fn test_embedded_prettierrc_is_valid_json() {
        let parsed: Result<serde_json::Value, _> = serde_json::from_str(NODEJS_PRETTIERRC);
        assert!(
            parsed.is_ok(),
            ".prettierrc should be valid JSON: {:?}",
            parsed.err()
        );
    }

    #[test]
    fn test_embedded_tsconfig_is_parseable() {
        // tsconfig.json uses JSON-with-comments (JSONC) which TypeScript supports
        // but serde_json does not. Verify it at least contains the expected keys.
        assert!(NODEJS_TSCONFIG_JSON.contains("compilerOptions"));
        assert!(NODEJS_TSCONFIG_JSON.contains("\"strict\": true"));
        assert!(NODEJS_TSCONFIG_JSON.contains("\"outDir\""));
    }

    #[test]
    fn test_embedded_qa_schema_is_valid_yaml() {
        // The schema is a multi-document YAML. Verify each document parses
        // individually via the iterator API.
        let mut count = 0;
        for document in serde_yaml::Deserializer::from_str(QA_SCHEMA_YAML) {
            let val = serde_yaml::Value::deserialize(document);
            assert!(
                val.is_ok(),
                "YAML document {} should parse: {:?}",
                count,
                val.err()
            );
            count += 1;
        }
        assert!(
            count >= 3,
            "Should have at least 3 YAML documents (standard, strict, minimal)"
        );
    }

    // -- CI workflow generation ---------------------------------------------

    #[test]
    fn test_ci_workflow_generation_rust() {
        let dir = TempDir::new().unwrap();
        let engine = TemplateEngine::with_override_dir(None);
        let opts = ScaffoldOptions {
            with_ci: true,
            ..Default::default()
        };

        let files = engine
            .scaffold_project("rust", "ci-test", dir.path(), &opts)
            .unwrap();
        assert!(files.contains(&".github/workflows/rust-qa.yml".to_string()));

        let wf_content =
            std::fs::read_to_string(dir.path().join(".github/workflows/rust-qa.yml")).unwrap();
        assert!(wf_content.contains("cargo check"));
        assert!(wf_content.contains("cargo clippy"));
    }

    #[test]
    fn test_ci_workflow_generation_python() {
        let dir = TempDir::new().unwrap();
        let engine = TemplateEngine::with_override_dir(None);
        let opts = ScaffoldOptions {
            with_ci: true,
            ..Default::default()
        };

        let files = engine
            .scaffold_project("python", "ci-test", dir.path(), &opts)
            .unwrap();
        assert!(files.contains(&".github/workflows/python-qa.yml".to_string()));
    }

    #[test]
    fn test_ci_workflow_generation_nodejs() {
        let dir = TempDir::new().unwrap();
        let engine = TemplateEngine::with_override_dir(None);
        let opts = ScaffoldOptions {
            with_ci: true,
            ..Default::default()
        };

        let files = engine
            .scaffold_project("nodejs", "ci-test", dir.path(), &opts)
            .unwrap();
        assert!(files.contains(&".github/workflows/nodejs-qa.yml".to_string()));
    }

    #[test]
    fn test_no_ci_when_disabled() {
        let dir = TempDir::new().unwrap();
        let engine = TemplateEngine::with_override_dir(None);
        let opts = ScaffoldOptions {
            with_ci: false,
            ..Default::default()
        };

        let files = engine
            .scaffold_project("rust", "no-ci", dir.path(), &opts)
            .unwrap();
        assert!(!files.iter().any(|f| f.contains(".github")));
    }

    #[test]
    fn test_no_tests_when_disabled() {
        let dir = TempDir::new().unwrap();
        let engine = TemplateEngine::with_override_dir(None);
        let opts = ScaffoldOptions {
            with_tests: false,
            ..Default::default()
        };

        let files = engine
            .scaffold_project("rust", "no-tests", dir.path(), &opts)
            .unwrap();
        assert!(!files.iter().any(|f| f.contains("tests/")));
    }

    // -- Interview integration ----------------------------------------------

    #[test]
    fn test_scaffold_from_context_rust() {
        use crate::interview::{InterviewContext, ProjectType, TestingPreference};

        let dir = TempDir::new().unwrap();
        let project_dir = dir.path().join("my-rust-app");
        std::fs::create_dir_all(&project_dir).unwrap();

        let ctx = InterviewContext {
            language: Some("Rust".into()),
            framework: Some("axum".into()),
            project_type: Some(ProjectType::WebApi),
            testing_preference: Some(TestingPreference::TestsAfter),
            output_dir: None,
            scope: None,
            extra_notes: vec![],
            task: "Build a REST API".into(),
        };

        let files = scaffold_from_context(&ctx, &project_dir).unwrap();
        assert!(files.contains(&"Cargo.toml".to_string()));
        assert!(files.contains(&"src/main.rs".to_string()));
    }

    #[test]
    fn test_scaffold_from_context_python() {
        use crate::interview::{InterviewContext, TestingPreference};

        let dir = TempDir::new().unwrap();
        let project_dir = dir.path().join("my-python-app");
        std::fs::create_dir_all(&project_dir).unwrap();

        let ctx = InterviewContext {
            language: Some("Python".into()),
            framework: None,
            project_type: None,
            testing_preference: Some(TestingPreference::Tdd),
            output_dir: None,
            scope: None,
            extra_notes: vec![],
            task: "A Python service".into(),
        };

        let files = scaffold_from_context(&ctx, &project_dir).unwrap();
        assert!(files.contains(&"pyproject.toml".to_string()));
    }

    #[test]
    fn test_scaffold_from_context_no_tests() {
        use crate::interview::{InterviewContext, TestingPreference};

        let dir = TempDir::new().unwrap();
        let project_dir = dir.path().join("no-tests-app");
        std::fs::create_dir_all(&project_dir).unwrap();

        let ctx = InterviewContext {
            language: Some("Rust".into()),
            framework: None,
            project_type: None,
            testing_preference: Some(TestingPreference::None),
            output_dir: None,
            scope: None,
            extra_notes: vec![],
            task: "Quick script".into(),
        };

        let files = scaffold_from_context(&ctx, &project_dir).unwrap();
        assert!(!files.iter().any(|f| f.contains("tests/")));
    }

    // -- Available templates ------------------------------------------------

    #[test]
    fn test_available_templates() {
        let templates = TemplateEngine::available_templates();
        assert_eq!(templates.len(), 3);
        assert!(templates.iter().any(|t| t.language == "rust"));
        assert!(templates.iter().any(|t| t.language == "python"));
        assert!(templates.iter().any(|t| t.language == "nodejs"));
    }

    // -- Unsupported language -----------------------------------------------

    #[test]
    fn test_scaffold_unsupported_language() {
        let dir = TempDir::new().unwrap();
        let engine = TemplateEngine::with_override_dir(None);
        let opts = ScaffoldOptions::default();

        let result = engine.scaffold_project("haskell", "test", dir.path(), &opts);
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("Unsupported language"));
    }

    // -- Runtime override ---------------------------------------------------

    #[test]
    fn test_runtime_override() {
        let dir = TempDir::new().unwrap();
        let override_dir = dir.path().join("overrides");
        let rust_dir = override_dir.join("rust");
        std::fs::create_dir_all(&rust_dir).unwrap();

        // Write a custom Cargo.toml override
        std::fs::write(
            rust_dir.join("Cargo.toml"),
            "[package]\nname = \"{{project_name}}\"\nversion = \"99.0.0\"\nedition = \"2021\"\n",
        )
        .unwrap();

        let engine = TemplateEngine::with_override_dir(Some(override_dir));
        let opts = ScaffoldOptions::default();
        let project_dir = dir.path().join("project");
        std::fs::create_dir_all(&project_dir).unwrap();

        let files = engine
            .scaffold_project("rust", "overridden", &project_dir, &opts)
            .unwrap();

        let cargo_content = std::fs::read_to_string(project_dir.join("Cargo.toml")).unwrap();
        assert!(
            cargo_content.contains("99.0.0"),
            "Should use the overridden template"
        );
    }
}