engenho-kube-codegen 0.53.192

OpenAPI v3 → typed Rust source generator for engenho-types. Reads BLAKE3-attested vendored K8s schemas + emits one Rust struct per kind with `impl KubeResource`. Generation over composition (Pillar 12).
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
//! Source emitters — typed config → Rust source string.
//!
//! Two entry points:
//!
//!   * [`emit_kind`]   — one kind's `.rs` file. Generates struct +
//!     `KubeResource` impl. Idempotent: same input always produces the
//!     same string (no clock, no env, no random).
//!   * [`emit_module`] — module-level `.rs` (e.g. `core_v1/mod.rs`)
//!     declaring every per-kind submodule in the group. Pure data-driven.

use std::collections::BTreeMap;
use std::fmt::Write as _;

use crate::catalog::{KindEntry, Subresource};
use crate::emit_typed::{SchemaView, emit_fields, emit_struct};
use crate::openapi::KindShape;

/// Generated-file header. Embedded into every emit so consumers can
/// recognize generator output + know what to expect on regenerate.
const HEADER: &str = "\
//! GENERATED — DO NOT EDIT by hand. Source: engenho-kube-codegen.
//!
//! Regenerate via `cargo run -p engenho-kube-codegen -- \\
//!     --schema engenho-types/vendor/openapi/v1.34.0 \\
//!     --output engenho-types/src/generated_v1_34`.
//!
//! Edit src/catalog.rs to add or remove kinds.

#![allow(clippy::module_name_repetitions)]

use std::borrow::Cow;
use serde::{Deserialize, Serialize};

use crate::kind::{GroupVersionKind, GroupVersionResource, KubeResource, Scope};
use crate::meta::ObjectMeta;
";

/// Emit the per-kind Rust source.
///
/// `description` is taken from the `OpenAPI` schema's `description`
/// field and inlined into the struct's rustdoc. Multiline doc
/// comments are prefixed with `///` per line (no smart wrapping —
/// upstream's doc strings are already wrapped at ~80).
#[must_use]
pub fn emit_kind(entry: &KindEntry, shape: &KindShape) -> String {
    let scope = if entry.cluster_scoped {
        "Scope::Cluster"
    } else {
        "Scope::Namespaced"
    };
    let api_version = if entry.group.is_empty() {
        entry.version.to_string()
    } else {
        format!("{}/{}", entry.group, entry.version)
    };
    // Use only the first paragraph of the OpenAPI description.
    // Subsequent paragraphs sometimes contain indented examples that
    // rustdoc interprets as Rust code blocks and tries to compile —
    // breaking `cargo test --doc`. Full description remains in the
    // vendored OpenAPI source.
    let doc = if shape.description.is_empty() {
        format!(
            "/// `{}/{}` typed kind — generated by engenho-kube-codegen.",
            api_version, entry.kind
        )
    } else {
        let first_para = shape
            .description
            .split("\n\n")
            .next()
            .unwrap_or(&shape.description);
        first_para
            .lines()
            .map(|l| {
                // Trim leading whitespace so rustdoc never sees indent
                // (the 4-space indent rule for code blocks).
                let trimmed = l.trim_start();
                if trimmed.is_empty() {
                    "///".to_string()
                } else {
                    format!("/// {trimmed}")
                }
            })
            .collect::<Vec<_>>()
            .join("\n")
    };
    format!(
        "{HEADER}\n\
{doc}\n\
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]\n\
pub struct {kind} {{\n\
    /// Standard object metadata.\n\
    #[serde(default, skip_serializing_if = \"is_empty_meta\")]\n\
    pub metadata: ObjectMeta,\n\
    /// Spec (typed expansion is M0.0.4; today opaque JSON).\n\
    #[serde(default, skip_serializing_if = \"serde_json::Value::is_null\")]\n\
    pub spec: serde_json::Value,\n\
    /// Status (typed expansion is M0.0.4; today opaque JSON).\n\
    #[serde(default, skip_serializing_if = \"Option::is_none\")]\n\
    pub status: Option<serde_json::Value>,\n\
}}\n\
\n\
impl KubeResource for {kind} {{\n\
    const GVK: GroupVersionKind = GroupVersionKind {{\n\
        group:   {group:?},\n\
        version: {version:?},\n\
        kind:    {kind:?},\n\
    }};\n\
    const GVR: GroupVersionResource = GroupVersionResource {{\n\
        group:    {group:?},\n\
        version:  {version:?},\n\
        resource: {resource:?},\n\
    }};\n\
    const SCOPE: Scope = {scope};\n\
\n\
    fn name(&self) -> Cow<'_, str> {{\n\
        Cow::Borrowed(self.metadata.name.as_str())\n\
    }}\n\
    fn namespace(&self) -> Option<Cow<'_, str>> {{\n\
        self.metadata.namespace.as_deref().map(Cow::Borrowed)\n\
    }}\n\
    fn resource_version(&self) -> Option<Cow<'_, str>> {{\n\
        if self.metadata.resource_version.is_empty() {{\n\
            None\n\
        }} else {{\n\
            Some(Cow::Borrowed(self.metadata.resource_version.as_str()))\n\
        }}\n\
    }}\n\
}}\n\
\n\
fn is_empty_meta(m: &ObjectMeta) -> bool {{ m == &ObjectMeta::default() }}\n\
",
        kind = entry.kind,
        group = entry.group,
        version = entry.version,
        resource = entry.resource,
    )
}

/// First-paragraph rustdoc from an `OpenAPI` description, `///`-prefixed and
/// left-trimmed (so rustdoc never sees an indented code block). Falls back to
/// a generated one-liner.
fn kind_doc(description: &str, api_version: &str, kind: &str) -> String {
    if description.is_empty() {
        return format!(
            "/// `{api_version}/{kind}` typed kind — generated by engenho-kube-codegen."
        );
    }
    let first = description.split("\n\n").next().unwrap_or(description);
    first
        .lines()
        .map(|l| {
            let t = l.trim_start();
            if t.is_empty() {
                "///".to_string()
            } else {
                format!("/// {t}")
            }
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// Emit the per-kind Rust source with TYPED fields + transitive sub-structs
/// (M0.0.4). Unlike [`emit_kind`] (opaque `spec: serde_json::Value`), this
/// walks the kind's `OpenAPI` `properties` into typed fields and recursively
/// emits every `$ref`'d sub-struct from `schemas` (the merged cross-group
/// schema map). apimachinery types are referenced from `crate::meta`; exotic
/// shapes bottom out at `serde_json::Value`, so the output always compiles.
///
/// Deterministic: same `(entry, kind_view, schemas)` → same string.
#[must_use]
pub fn emit_kind_typed(
    entry: &KindEntry,
    kind_view: &SchemaView,
    schemas: &BTreeMap<String, SchemaView>,
) -> String {
    let scope = if entry.cluster_scoped {
        "Scope::Cluster"
    } else {
        "Scope::Namespaced"
    };
    let api_version = if entry.group.is_empty() {
        entry.version.to_string()
    } else {
        format!("{}/{}", entry.group, entry.version)
    };
    let doc = kind_doc(&kind_view.description, &api_version, entry.kind);

    // Typed fields of the kind itself + the set of referenced schema keys.
    // Sub-structs live in the shared `types` module (emitted once, globally
    // deduped) — `schemas` is unused here now but kept in the signature so
    // callers don't change when sub-struct resolution moves back inline.
    let _ = schemas;
    let mut refs = std::collections::BTreeSet::new();
    let fields = emit_fields(
        entry.openapi_key,
        &kind_view.properties,
        &kind_view.required,
        &mut refs,
    );

    // Bring the shared sub-structs into scope when this kind references any.
    let shared_import = if refs.is_empty() {
        String::new()
    } else {
        "use crate::generated_v1_34::types::*;\n".to_string()
    };

    format!(
        "{HEADER}{shared_import}\n\
{doc}\n\
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]\n\
pub struct {kind} {{\n\
{fields}}}\n\
\n\
impl KubeResource for {kind} {{\n\
    const GVK: GroupVersionKind = GroupVersionKind {{\n\
        group:   {group:?},\n\
        version: {version:?},\n\
        kind:    {kind:?},\n\
    }};\n\
    const GVR: GroupVersionResource = GroupVersionResource {{\n\
        group:    {group:?},\n\
        version:  {version:?},\n\
        resource: {resource:?},\n\
    }};\n\
    const SCOPE: Scope = {scope};\n\
\n\
    fn name(&self) -> Cow<'_, str> {{\n\
        Cow::Borrowed(self.metadata.name.as_str())\n\
    }}\n\
    fn namespace(&self) -> Option<Cow<'_, str>> {{\n\
        self.metadata.namespace.as_deref().map(Cow::Borrowed)\n\
    }}\n\
    fn resource_version(&self) -> Option<Cow<'_, str>> {{\n\
        if self.metadata.resource_version.is_empty() {{\n\
            None\n\
        }} else {{\n\
            Some(Cow::Borrowed(self.metadata.resource_version.as_str()))\n\
        }}\n\
    }}\n\
}}\n\
\n\
fn is_empty_meta(m: &ObjectMeta) -> bool {{ m == &ObjectMeta::default() }}\n",
        kind = entry.kind,
        group = entry.group,
        version = entry.version,
        resource = entry.resource,
    )
}

/// Header for the shared sub-struct module (`generated_v1_34/types.rs`).
const SHARED_HEADER: &str = "\
//! GENERATED — DO NOT EDIT by hand. Source: engenho-kube-codegen.
//!
//! Shared sub-structs referenced by the generated kinds — emitted once,
//! globally deduplicated, so every kind references one canonical type.

#![allow(clippy::module_name_repetitions)]

use serde::{Deserialize, Serialize};
";

/// Emit the shared sub-struct module: every transitively-referenced sub-struct
/// (deduped) as one canonical `pub struct`. Sub-structs reference each other by
/// bare name (same module); `ObjectMeta` + curated enums via absolute paths.
///
/// `catalog` lets the module import the catalog KINDS that shared sub-structs
/// reference as field types (e.g. `StatefulSetSpec.volumeClaimTemplates:
/// Vec<PersistentVolumeClaim>`) — only those actually referenced, so no unused
/// imports.
#[must_use]
pub fn emit_shared_module(
    shared: &[(String, String, SchemaView)],
    catalog: &[KindEntry],
) -> String {
    let mut out = String::from(SHARED_HEADER);

    // Which catalog kinds do the shared sub-structs reference as field types?
    let mut referenced_keys = std::collections::BTreeSet::new();
    for (_, key, view) in shared {
        let mut r = std::collections::BTreeSet::new();
        let _ = emit_fields(key, &view.properties, &view.required, &mut r);
        referenced_keys.extend(r);
    }
    for e in catalog {
        if referenced_keys.contains(e.openapi_key) {
            let _ = writeln!(out, "use crate::generated_v1_34::{}::{};", e.module, e.kind);
        }
    }

    for (name, key, view) in shared {
        let (src, _) = emit_struct(name, key, view);
        out.push('\n');
        out.push_str(&src);
    }
    // Only emit the metadata helper if some sub-struct actually skips on it.
    if out.contains("\"is_empty_meta\"") {
        out.push_str(
            "\nfn is_empty_meta(m: &crate::meta::ObjectMeta) -> bool { m == &crate::meta::ObjectMeta::default() }\n",
        );
    }
    out
}

/// Header for the runtime catalog module (`generated_v1_34/catalog.rs`).
const CATALOG_HEADER: &str = "\
//! GENERATED — DO NOT EDIT by hand. Source: engenho-kube-codegen.
//!
//! Runtime-iterable resource catalog — one [`ResourceDescriptor`] per
//! generated kind. The apiserver folds [`RESOURCE_CATALOG`] to build
//! handlers, register routes, and serve discovery; the curated plural
//! (`KindEntry.resource`) flows verbatim into every consumer so there is
//! ONE source of truth for pluralization (no `+s` derivation).
//!
//! Regenerate via `cargo run -p engenho-kube-codegen -- \\
//!     --schema engenho-types/vendor/openapi/v1.34.0 \\
//!     --output engenho-types/src/generated_v1_34`.
//!
//! Edit src/catalog.rs to add or remove kinds.

use crate::kind::{GroupVersionKind, GroupVersionResource, Scope};
";

/// Body of the runtime `ResourceDescriptor` type + its `to_gvk`/`to_gvr`
/// helpers. Kept as a fixed string so the generated catalog is fully
/// self-contained (the apiserver depends on `engenho-types`, never on the
/// codegen crate) and byte-deterministic.
const CATALOG_TYPE_DECL: &str = "\
/// A K8s subresource a kind serves under `<plural>/<name>/<sub>`.
///
/// Typed — NOT a string — so a bad combination is unrepresentable: the
/// discovery emitter, the router dispatch, and the store-scoping handler all
/// `match` on this enum, and the compiler refuses any value outside the
/// closed set. `Status` is the `/status` subresource (controller-written
/// status, isolated from spec on write); `Scale` is the autoscaling/v1
/// `/scale` subresource (the projected replica view).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Subresource {
    /// `/status` — get/patch/update the `.status` only (spec untouched).
    Status,
    /// `/scale` — get/patch/update the autoscaling/v1 Scale projection
    /// (`spec.replicas` only).
    Scale,
    /// `/log` — GET a Pod container's stdout/stderr (`kubectl logs`). Read-only
    /// (GET only). Pod-only; the router dispatches it to the kubelet
    /// (single-node: in-process) which reads `backend.logs`.
    Log,
    /// `/token` — POST a `TokenRequest`, receive a signed ServiceAccount JWT
    /// (`kubectl create token`, and every in-cluster client's identity).
    ///
    /// The ONLY create-shaped subresource: status/scale/log are read or
    /// update shapes, so the router's blanket \"POST on a subresource is not
    /// a CREATE\" rule has exactly this exception. It is also the only one
    /// whose response body is not the stored object — nothing is persisted,
    /// the minted token is returned in `.status.token` and never stored.
    Token,
    /// `/exec` — WebSocket stream relayed to the node kubelet.
    Exec,
    /// `/attach` — WebSocket stream relayed to the node kubelet.
    Attach,
    /// `/portforward` — WebSocket stream relayed to the node kubelet.
    PortForward,
    /// `/eviction` — POST a policy/v1 `Eviction`: delete the pod unless a
    /// PodDisruptionBudget forbids it (429). Create-only, Pod-only.
    Eviction,
}

/// One runtime row describing a routable/discoverable Kubernetes kind.
///
/// `plural` is the curated URL segment (`KindEntry.resource`) — irregular
/// plurals (e.g. `Endpoints` → `endpoints`) are correct by construction.
/// `api_version` is `\"v1\"` for the core group, `\"<group>/<version>\"`
/// otherwise — precomputed so consumers never re-derive it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ResourceDescriptor {
    /// API group (`\"\"` for core/v1).
    pub group: &'static str,
    /// API version (`\"v1\"`, …).
    pub version: &'static str,
    /// Kind (`\"Pod\"`, `\"Deployment\"`, …).
    pub kind: &'static str,
    /// Plural URL segment (`\"pods\"`, `\"endpoints\"`, …) — curated, never `+s`.
    pub plural: &'static str,
    /// `true` ⇒ namespaced; `false` ⇒ cluster-scoped.
    pub namespaced: bool,
    /// `\"v1\"` for core, `\"<group>/<version>\"` otherwise.
    pub api_version: &'static str,
    /// kubectl short-name aliases (e.g. `[\"deploy\"]`). Empty for kinds
    /// with no upstream short name. Pure registration metadata (NOT in the
    /// OpenAPI schema) — flows into discovery `shortNames`.
    pub short_names: &'static [&'static str],
    /// Singular resource name (lowercase kind) — served as discovery
    /// `singularName`.
    pub singular: &'static str,
    /// kubectl resource categories (e.g. `[\"all\"]`). Empty for kinds in
    /// no category. Flows into discovery `categories`.
    pub categories: &'static [&'static str],
    /// `true` ⇒ this kind has NO vendored OpenAPI v3 schema document and NO
    /// typed struct — it is served as opaque JSON via the generic
    /// `StoreBackedHandler` (e.g.
    /// `apiextensions.k8s.io/v1.CustomResourceDefinition`, stored as plain
    /// JSON). Such kinds are routable + discoverable but absent from the
    /// `/openapi/v3` served set, so the ★★ CATALOG-REFLECTION invariant
    /// (`SERVED (group,version) == non-opaque RESOURCE_CATALOG (group,version)`)
    /// excludes them. `kubectl apply` of an opaque kind needs
    /// `--validate=false` (no schema to validate against); `kubectl explain`
    /// is unavailable. Non-opaque kinds are `false`.
    pub opaque: bool,
    /// The subresources this kind serves under `<plural>/<name>/<sub>`
    /// (`/status`, `/scale`). Typed slice — the SINGLE source the router
    /// dispatch, the store-scoping handler, and discovery all read; no kind
    /// is ever special-cased by name. `&[]` for kinds with no subresource.
    pub subresources: &'static [Subresource],
}

impl ResourceDescriptor {
    /// `true` iff this kind serves the `/status` subresource.
    #[must_use]
    pub fn has_status(&self) -> bool {
        self.subresources.contains(&Subresource::Status)
    }

    /// `true` iff this kind serves the autoscaling/v1 `/scale` subresource.
    #[must_use]
    pub fn has_scale(&self) -> bool {
        self.subresources.contains(&Subresource::Scale)
    }

    /// `true` iff this kind serves the `/log` subresource (Pod only).
    #[must_use]
    pub fn has_log(&self) -> bool {
        self.subresources.contains(&Subresource::Log)
    }

    /// The Group/Version/Kind triple for this descriptor.
    #[must_use]
    pub const fn to_gvk(&self) -> GroupVersionKind {
        GroupVersionKind {
            group: self.group,
            version: self.version,
            kind: self.kind,
        }
    }

    /// The Group/Version/Resource triple for this descriptor.
    #[must_use]
    pub const fn to_gvr(&self) -> GroupVersionResource {
        GroupVersionResource {
            group: self.group,
            version: self.version,
            resource: self.plural,
        }
    }

    /// The runtime [`Scope`] for this descriptor.
    #[must_use]
    pub const fn scope(&self) -> Scope {
        if self.namespaced {
            Scope::Namespaced
        } else {
            Scope::Cluster
        }
    }
}
";

/// Emit `generated_v1_34/catalog.rs`: the runtime [`ResourceDescriptor`]
/// type + `pub const RESOURCE_CATALOG` with one row per `catalog` entry.
///
/// The plural is `entry.resource` verbatim (the curated, correct plural);
/// `namespaced = !entry.cluster_scoped`; `api_version = entry.version` for
/// the core group else `"<group>/<version>"`. Deterministic: same catalog →
/// same string (iteration follows the static `KIND_CATALOG` order).
#[must_use]
pub fn emit_catalog(catalog: &[KindEntry]) -> String {
    let mut out = String::from(CATALOG_HEADER);
    out.push('\n');
    out.push_str(CATALOG_TYPE_DECL);
    out.push('\n');
    out.push_str(
        "/// Every routable/discoverable kind, in `KIND_CATALOG` order.\n\
         pub const RESOURCE_CATALOG: &[ResourceDescriptor] = &[\n",
    );
    for e in catalog {
        let api_version = if e.group.is_empty() {
            e.version.to_string()
        } else {
            format!("{}/{}", e.group, e.version)
        };
        let _ = writeln!(
            out,
            "    ResourceDescriptor {{ group: {:?}, version: {:?}, kind: {:?}, plural: {:?}, namespaced: {}, api_version: {:?}, short_names: {}, singular: {:?}, categories: {}, opaque: {}, subresources: {} }},",
            e.group,
            e.version,
            e.kind,
            e.resource,
            !e.cluster_scoped,
            api_version,
            render_str_slice(e.short_names),
            e.singular,
            render_str_slice(e.categories),
            e.opaque,
            render_subresources(e.subresources),
        );
    }
    out.push_str("];\n");
    out
}

/// Render a `&'static [&'static str]` as the Rust slice literal that
/// reconstructs it: `&[]` for empty, `&["a", "b"]` otherwise. Each element
/// is rendered through `{:?}` (the typed string-debug surface) so the
/// output is a valid, escaped Rust string literal and byte-deterministic.
/// This is the typed slice renderer the ★★ TYPED EMISSION rule requires for
/// emitting `&[&str]` constants — no hand-built quoting.
fn render_str_slice(items: &[&str]) -> String {
    if items.is_empty() {
        return "&[]".to_string();
    }
    let joined = items
        .iter()
        .map(|s| format!("{s:?}"))
        .collect::<Vec<_>>()
        .join(", ");
    format!("&[{joined}]")
}

/// Render a `&'static [Subresource]` as the Rust slice literal that
/// reconstructs it: `&[]` for empty, `&[Subresource::Status,
/// Subresource::Scale]` otherwise. Each variant is rendered through a typed
/// `match` (NOT a debug-format guess) so the emitted path is exactly the
/// generated `Subresource` enum's variant name — the typed slice renderer
/// the ★★ TYPED EMISSION rule requires (peer of [`render_str_slice`]).
fn render_subresources(items: &[Subresource]) -> String {
    if items.is_empty() {
        return "&[]".to_string();
    }
    let joined = items
        .iter()
        .map(|s| match s {
            Subresource::Status => "Subresource::Status",
            Subresource::Scale => "Subresource::Scale",
            Subresource::Log => "Subresource::Log",
            Subresource::Token => "Subresource::Token",
            Subresource::Exec => "Subresource::Exec",
            Subresource::Attach => "Subresource::Attach",
            Subresource::PortForward => "Subresource::PortForward",
            Subresource::Eviction => "Subresource::Eviction",
        })
        .collect::<Vec<_>>()
        .join(", ");
    format!("&[{joined}]")
}

/// Emit a module-level `mod.rs` listing every per-kind submodule in
/// `entries` (typically all entries with the same `module` field).
///
/// `module_name` ⇒ the module path (e.g. `core_v1`); used only in the
/// header comment.
#[must_use]
pub fn emit_module(module_name: &str, entries: &[&KindEntry]) -> String {
    let mut out =
        format!("//! GENERATED — `{module_name}` typed kinds. Source: engenho-kube-codegen.\n\n");
    for e in entries {
        let _ = writeln!(out, "mod {};", e.kind.to_lowercase());
    }
    out.push('\n');
    for e in entries {
        let _ = writeln!(out, "pub use {}::{};", e.kind.to_lowercase(), e.kind);
    }
    // Re-export the shared sub-structs at the group level so consumers can
    // import e.g. `core_v1::PodSpec` / `apps_v1::DeploymentSpec` (one canonical
    // type, re-exported from every group that references it).
    out.push_str("\npub use crate::generated_v1_34::types::*;\n");
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::openapi::{KindShape, XGvk};
    use std::collections::BTreeMap;

    fn entry() -> KindEntry {
        KindEntry {
            kind: "Pod",
            openapi_key: "io.k8s.api.core.v1.Pod",
            group: "",
            version: "v1",
            resource: "pods",
            cluster_scoped: false,
            module: "core_v1",
            short_names: &["po"],
            singular: "pod",
            categories: &["all"],
            opaque: false,
            subresources: &[Subresource::Status],
        }
    }

    fn shape() -> KindShape {
        KindShape {
            gvks: vec![XGvk {
                group: String::new(),
                version: "v1".into(),
                kind: "Pod".into(),
            }],
            description: "Pod is a collection of containers that can run on a host.".into(),
            properties: BTreeMap::new(),
            required: vec![],
        }
    }

    #[test]
    fn emit_kind_contains_struct_decl() {
        let s = emit_kind(&entry(), &shape());
        assert!(s.contains("pub struct Pod"));
        assert!(s.contains("impl KubeResource for Pod"));
    }

    #[test]
    fn emit_kind_namespaced_scope() {
        let s = emit_kind(&entry(), &shape());
        assert!(s.contains("Scope::Namespaced"));
    }

    #[test]
    fn emit_kind_cluster_scoped_when_flag_set() {
        let mut e = entry();
        e.cluster_scoped = true;
        e.kind = "Namespace";
        e.resource = "namespaces";
        let s = emit_kind(&e, &shape());
        assert!(s.contains("Scope::Cluster"));
        assert!(s.contains("pub struct Namespace"));
    }

    #[test]
    fn emit_kind_resource_in_gvr() {
        let s = emit_kind(&entry(), &shape());
        assert!(s.contains(r#"resource: "pods""#));
    }

    #[test]
    fn emit_kind_doc_from_openapi_description() {
        let s = emit_kind(&entry(), &shape());
        assert!(s.contains("Pod is a collection of containers"));
    }

    #[test]
    fn emit_kind_is_deterministic() {
        let s1 = emit_kind(&entry(), &shape());
        let s2 = emit_kind(&entry(), &shape());
        assert_eq!(s1, s2);
    }

    #[test]
    fn emit_catalog_has_one_row_per_entry() {
        use crate::catalog::KIND_CATALOG;
        let src = emit_catalog(KIND_CATALOG);
        // Count the const rows specifically — they are the only lines that
        // open with the 4-space-indented descriptor literal. The struct
        // decl + impl block use `pub struct` / `impl`, not this prefix.
        let rows = src.matches("    ResourceDescriptor { group:").count();
        assert_eq!(
            rows,
            KIND_CATALOG.len(),
            "one RESOURCE_CATALOG row per KIND_CATALOG entry"
        );
    }

    #[test]
    fn emit_catalog_uses_curated_plural_not_plus_s() {
        use crate::catalog::KIND_CATALOG;
        let src = emit_catalog(KIND_CATALOG);
        // Endpoints is the canonical irregular kind: the curated plural is
        // "endpoints", NOT the naive "endpointss".
        assert!(
            src.contains(r#"kind: "Endpoints", plural: "endpoints""#),
            "Endpoints row carries the curated plural"
        );
        assert!(
            !src.contains("endpointss"),
            "no naive +s pluralization survives in the catalog"
        );
    }

    #[test]
    fn emit_catalog_api_version_core_vs_grouped() {
        use crate::catalog::KIND_CATALOG;
        let src = emit_catalog(KIND_CATALOG);
        // core kind → api_version "v1".
        assert!(
            src.contains(r#"kind: "Pod", plural: "pods", namespaced: true, api_version: "v1""#)
        );
        // grouped kind → "<group>/<version>".
        assert!(src.contains(
            r#"kind: "Deployment", plural: "deployments", namespaced: true, api_version: "apps/v1""#
        ));
    }

    #[test]
    fn emit_catalog_namespaced_flag_matches_scope() {
        use crate::catalog::KIND_CATALOG;
        let src = emit_catalog(KIND_CATALOG);
        // Cluster-scoped Namespace → namespaced: false.
        assert!(
            src.contains(r#"kind: "Namespace", plural: "namespaces", namespaced: false"#),
            "cluster-scoped Namespace → namespaced: false"
        );
    }

    #[test]
    fn emit_catalog_is_deterministic() {
        use crate::catalog::KIND_CATALOG;
        assert_eq!(emit_catalog(KIND_CATALOG), emit_catalog(KIND_CATALOG));
    }

    #[test]
    fn opaque_crd_kind_is_catalog_only_no_module_struct() {
        // The apiextensions CRD kind is OPAQUE: it appears as a
        // RESOURCE_CATALOG row (so routing + discovery light up) but has NO
        // `module` / `openapi_key`, so the generator emits no per-kind
        // struct for it. This is the ★★ CATALOG-REFLECTION invariant for
        // the opaque seam — a regression where the CRD row gained a module
        // would break codegen (no vendored schema), so pin both facts.
        use crate::catalog::KIND_CATALOG;
        let crd = KIND_CATALOG
            .iter()
            .find(|e| e.kind == "CustomResourceDefinition")
            .expect("CustomResourceDefinition cataloged");
        assert!(crd.opaque, "CRD kind is opaque (no typed struct)");
        assert!(crd.module.is_empty(), "opaque CRD has no module");
        assert!(crd.openapi_key.is_empty(), "opaque CRD has no openapi_key");
        assert_eq!(crd.group, "apiextensions.k8s.io");
        assert_eq!(crd.resource, "customresourcedefinitions");
        assert!(crd.cluster_scoped, "CRDs are cluster-scoped");
        // The catalog row IS emitted (descriptor present) even though no
        // module struct is.
        let src = emit_catalog(KIND_CATALOG);
        assert!(
            src.contains(
                r#"kind: "CustomResourceDefinition", plural: "customresourcedefinitions""#
            ),
            "opaque CRD still gets a RESOURCE_CATALOG row"
        );
    }

    #[test]
    fn every_singular_is_lowercase_kind() {
        use crate::catalog::KIND_CATALOG;
        for e in KIND_CATALOG {
            assert_eq!(
                e.singular,
                e.kind.to_lowercase(),
                "{}: singular must be the lowercased kind",
                e.kind
            );
        }
    }

    #[test]
    fn emit_catalog_renders_short_names_singular_categories() {
        use crate::catalog::KIND_CATALOG;
        let src = emit_catalog(KIND_CATALOG);
        // Deployment: deploy short name + all category.
        assert!(
            src.contains(
                r#"kind: "Deployment", plural: "deployments", namespaced: true, api_version: "apps/v1", short_names: &["deploy"], singular: "deployment", categories: &["all"]"#
            ),
            "Deployment row carries deploy/deployment/all"
        );
        // Secret: NO short name (empty slice literal) + no category.
        assert!(
            src.contains(
                r#"kind: "Secret", plural: "secrets", namespaced: true, api_version: "v1", short_names: &[], singular: "secret", categories: &[]"#
            ),
            "Secret row carries an empty short_names + categories slice"
        );
        // Pod: po short name + all category (core kind).
        assert!(
            src.contains(r#"short_names: &["po"], singular: "pod", categories: &["all"]"#),
            "Pod row carries po/pod/all"
        );
    }

    #[test]
    fn render_str_slice_empty_and_nonempty() {
        assert_eq!(render_str_slice(&[]), "&[]");
        assert_eq!(render_str_slice(&["deploy"]), r#"&["deploy"]"#);
        assert_eq!(render_str_slice(&["a", "b"]), r#"&["a", "b"]"#);
    }

    #[test]
    fn render_subresources_empty_status_and_both() {
        assert_eq!(render_subresources(&[]), "&[]");
        assert_eq!(
            render_subresources(&[Subresource::Status]),
            "&[Subresource::Status]"
        );
        assert_eq!(
            render_subresources(&[Subresource::Status, Subresource::Scale]),
            "&[Subresource::Status, Subresource::Scale]"
        );
    }

    #[test]
    fn emit_catalog_renders_subresource_slices() {
        use crate::catalog::KIND_CATALOG;
        let src = emit_catalog(KIND_CATALOG);
        // Deployment carries Status + Scale (scalable workload).
        assert!(
            src.contains(r#"kind: "Deployment""#)
                && src.contains("subresources: &[Subresource::Status, Subresource::Scale]"),
            "Deployment row carries Status + Scale"
        );
        // DaemonSet carries Status only (not scalable).
        assert!(
            src.contains(
                r#"kind: "DaemonSet", plural: "daemonsets", namespaced: true, api_version: "apps/v1", short_names: &["ds"], singular: "daemonset", categories: &["all"], opaque: false, subresources: &[Subresource::Status]"#
            ),
            "DaemonSet row carries Status only"
        );
        // ConfigMap carries no subresource (empty slice).
        assert!(
            src.contains(
                r#"kind: "ConfigMap", plural: "configmaps", namespaced: true, api_version: "v1", short_names: &["cm"], singular: "configmap", categories: &[], opaque: false, subresources: &[]"#
            ),
            "ConfigMap row carries an empty subresources slice"
        );
        // The emitted enum decl is present (so the generated catalog compiles
        // against its own typed Subresource).
        assert!(
            src.contains("pub enum Subresource"),
            "the generated catalog emits the Subresource enum decl"
        );
    }

    #[test]
    fn emit_module_lists_each_kind() {
        let entries: Vec<KindEntry> = vec![
            entry(),
            KindEntry {
                kind: "Service",
                openapi_key: "io.k8s.api.core.v1.Service",
                group: "",
                version: "v1",
                resource: "services",
                cluster_scoped: false,
                module: "core_v1",
                short_names: &["svc"],
                singular: "service",
                categories: &["all"],
                opaque: false,
                subresources: &[Subresource::Status],
            },
        ];
        let refs: Vec<&KindEntry> = entries.iter().collect();
        let m = emit_module("core_v1", &refs);
        assert!(m.contains("mod pod;"));
        assert!(m.contains("mod service;"));
        assert!(m.contains("pub use pod::Pod;"));
        assert!(m.contains("pub use service::Service;"));
    }
}