Skip to main content

crossplane_forge/
controller_gen.rs

1//! Crossplane controller emitter — produces a per-resource controller
2//! `.go` file implementing the `crossplane-runtime` `ExternalClient`
3//! interface (Observe / Create / Update / Delete) plus the manager-
4//! wiring `Setup` function and the `connector` that resolves a
5//! `ProviderConfig` into an `external` client.
6//!
7//! Built entirely on top of [`go_synthesizer`] — the file is
8//! constructed as a typed [`GoFile`] tree, never as `format!()`
9//! strings of Go syntax.
10
11use std::collections::BTreeMap;
12
13use go_synthesizer::{
14    GoBlock, GoDecl, GoExpr, GoField, GoFile, GoFuncDecl, GoImport, GoLit, GoParam, GoRecv,
15    GoStmt, GoStructTag, GoType, GoTypeBody, GoTypeDecl, JsonTag, print_file,
16};
17use crate::body_signatures::{FieldMatch, SharedBodySigMap};
18use iac_forge::ir::{IacProvider, IacResource, IacType};
19use iac_forge::naming::{strip_provider_prefix, to_pascal_case};
20use iac_forge::sdk_naming;
21
22/// Configuration the emitter needs alongside the IR — primarily where
23/// to import the SDK from and where to import the per-provider /
24/// per-resource v1alpha1 types from.
25#[derive(Debug, Clone)]
26#[non_exhaustive]
27pub struct ControllerConfig {
28    /// Go module path for the SDK the controllers call into.
29    pub sdk_module: String,
30    /// Go module path for the generated CRD types this provider emits.
31    pub provider_module: String,
32    /// API group for the CRDs (Crossplane convention is
33    /// `<provider>.crossplane.io`).
34    pub api_group: String,
35    /// API version for the emitted CRDs (e.g., `v1alpha1`).
36    pub api_version: String,
37    /// Per-resource shape overrides — keyed by the bare resource name
38    /// (after `strip_provider_prefix`, before snake_case): e.g.
39    /// `"esm"`, `"role_rule"`. Used by the controller emitter to
40    /// override the default `Name string` body-field assumption.
41    /// Resources not present in this map use `ResourceShape::default()`.
42    pub resource_shapes: BTreeMap<String, ResourceShape>,
43    /// M6.4 — schema-driven body-field signature lookup.
44    ///
45    /// When `Some`, the M6.2 broad walk in `build_request_body`
46    /// consults this map for every scalar attribute it would push
47    /// onto an SDK body composite. If the SDK body schema lacks the
48    /// field OR the openapi type/required-ness disagrees with the
49    /// IacAttribute, the push is silently skipped — restoring 100%
50    /// `go build` coverage across the corpus regardless of TOML/SDK
51    /// schema divergences.
52    ///
53    /// When `None`, the broad walk falls back to the per-resource
54    /// `push_for_provider_fields` opt-in flag (default off).
55    pub body_sigs: crate::body_signatures::SharedBodySigMap,
56}
57
58/// Per-resource shape configuration consumed by the controller
59/// emitter. Captures the heterogeneity across SDK body types — some
60/// use `Name string`, some `Name *string`, some a different field
61/// entirely (e.g. `EsmName`, `UscName`, `Path`), and some use
62/// composite keys / mixed-per-CRUD identifiers that don't fit the
63/// single-identifier pattern.
64#[derive(Debug, Clone, PartialEq, Eq)]
65#[non_exhaustive]
66pub struct ResourceShape {
67    /// Default body-field name carrying the resource identifier
68    /// (defaults to `"Name"`). Per-CRUD-method overrides in
69    /// `per_method` win when present.
70    pub identifier_field: String,
71    /// Default for whether the identifier field is `*string` instead
72    /// of `string`. Per-CRUD-method overrides in `per_method` win.
73    pub identifier_pointer: bool,
74    /// Per-CRUD-method overrides — populated for resources whose SDK
75    /// body shape varies per method (e.g. `kmip_client.Name string`
76    /// on Create vs `*string` on Read/Delete).
77    pub per_method: BTreeMap<CrudMethod, MethodOverride>,
78    /// Emit a stub controller (no SDK calls) for resources whose body
79    /// shape requires composite keys / mixed-int64-vs-string IDs /
80    /// singleton bodies that ResourceShape can't yet express. Stubs
81    /// satisfy the ExternalClient interface but no-op every method.
82    pub stub: bool,
83    /// M6.2 broad walk — when true, Create+Update bodies push every
84    /// non-computed non-identifier scalar attribute from
85    /// `cr.Spec.ForProvider.X` onto the SDK body composite.
86    ///
87    /// Default false because the akeyless TOML's IacType disagrees
88    /// with the akeyless-go SDK body's Go type for several common
89    /// fields (DeleteProtection bool/string, RotationHour int64/int32,
90    /// UseTls bool/string, TargetName/RotatorType missing on Update,
91    /// etc.) — naïve broad-walk produces compile errors on ~62% of
92    /// the 119-resource corpus. Resources opt in only after their
93    /// type alignment + `body_field_skips` are verified by `go build`.
94    ///
95    /// M6.4 (schema-driven filtering) will replace this opt-in flag
96    /// by reading the SDK body schema from the OpenAPI spec at emit
97    /// time and auto-skipping fields whose name+type don't match.
98    pub push_for_provider_fields: bool,
99}
100
101/// Which CRUD method an override applies to.
102#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
103#[non_exhaustive]
104pub enum CrudMethod {
105    Read,
106    Create,
107    Update,
108    Delete,
109}
110
111/// Per-method override of [`ResourceShape`]'s defaults.
112#[derive(Debug, Clone, PartialEq, Eq, Default)]
113#[non_exhaustive]
114pub struct MethodOverride {
115    /// When `Some`, replaces `ResourceShape::identifier_field` for
116    /// this CRUD method.
117    pub identifier_field: Option<String>,
118    /// When `Some`, replaces `ResourceShape::identifier_pointer` for
119    /// this CRUD method.
120    pub identifier_pointer: Option<bool>,
121    /// When `Some`, the entire body construction goes through the
122    /// template, ignoring `identifier_field` / `identifier_pointer`.
123    /// Used for SDK body shapes that don't fit the
124    /// single-string-identifier pattern.
125    pub body_template: Option<BodyTemplate>,
126    /// PascalCase attribute names to skip when M6.2 walks
127    /// `cr.Spec.ForProvider.*` to push fields onto the SDK body.
128    ///
129    /// Used for the per-resource per-method skip list when the TOML's
130    /// IacType disagrees with the SDK body's Go type — e.g. the TOML
131    /// says `Boolean` but the akeyless OpenAPI spec defines the same
132    /// JSON property as `*string`. Without this skip, the emitted
133    /// `body.X = cr.Spec.ForProvider.X` triggers a Go type-mismatch.
134    ///
135    /// Slice 2 graduates this to schema-driven filtering by reading
136    /// the SDK body schema from the OpenAPI spec at emit time and
137    /// auto-skipping fields whose name+type don't match.
138    pub body_field_skips: Vec<String>,
139}
140
141/// Body-construction template for a CRUD method whose SDK body
142/// shape doesn't fit the single-string-identifier pattern.
143#[derive(Debug, Clone, PartialEq, Eq)]
144#[non_exhaustive]
145pub enum BodyTemplate {
146    /// `body := akeyless.X{Token: &e.token}` — no identifier field.
147    /// Used by singleton-bodies (e.g. KmipDescribeServer / KmipDeleteServer).
148    NoIdentifier,
149    /// `id, _ := strconv.ParseInt(meta.GetExternalName(cr), 10, 64)` +
150    /// `body := akeyless.X{<field>: id, Token: &e.token}`. Adds `strconv`
151    /// to the controller's imports.
152    Int64FromExternalName { field: String },
153    /// `body := akeyless.X{<body_field>: cr.Spec.ForProvider.<spec_field>,
154    ///                    ..., Token: &e.token}` — composite-key bodies
155    /// pulling each field from the resource's spec.
156    SpecFields(Vec<SpecFieldMapping>),
157}
158
159/// One (body_field, spec_field, pointer) triple for [`BodyTemplate::SpecFields`].
160#[derive(Debug, Clone, PartialEq, Eq)]
161#[non_exhaustive]
162pub struct SpecFieldMapping {
163    /// SDK body struct field name (e.g. `"RoleName"`).
164    pub body_field: String,
165    /// Go-PascalCase'd `cr.Spec.ForProvider.<X>` field name
166    /// (e.g. `"RoleName"`, `"Path"`, `"AmName"`). The emitter does not
167    /// transform — pass the exact Go identifier the IR produces.
168    pub spec_field: String,
169    /// Whether the SDK body field is `*T` (pointer) — emitter wraps
170    /// the spec value in a `&`.
171    pub pointer: bool,
172}
173
174/// The resolved (post-`per_method`-lookup) shape for one CRUD method.
175#[derive(Debug, Clone, PartialEq, Eq)]
176pub struct EffectiveShape {
177    pub identifier_field: String,
178    pub identifier_pointer: bool,
179    pub body_template: Option<BodyTemplate>,
180    /// PascalCase attribute names skipped by the M6.2 broad walk for
181    /// this method.
182    pub body_field_skips: Vec<String>,
183}
184
185impl Default for ResourceShape {
186    fn default() -> Self {
187        Self {
188            identifier_field: "Name".to_string(),
189            identifier_pointer: false,
190            per_method: BTreeMap::new(),
191            stub: false,
192            push_for_provider_fields: false,
193        }
194    }
195}
196
197impl ResourceShape {
198    /// Body-field with `*string` identifier (e.g. `Name *string`).
199    #[must_use]
200    pub fn name_pointer() -> Self {
201        Self {
202            identifier_pointer: true,
203            ..Self::default()
204        }
205    }
206
207    /// Body-field with a non-`Name` `string` identifier
208    /// (e.g. `EsmName`, `UscName`, `Path`, `Hostname`).
209    #[must_use]
210    pub fn alt_field(field: impl Into<String>) -> Self {
211        Self {
212            identifier_field: field.into(),
213            ..Self::default()
214        }
215    }
216
217    /// Stub controller — body shape doesn't fit any expressible
218    /// `ResourceShape`; deeper M3.2 graduation needed.
219    #[must_use]
220    pub fn stub() -> Self {
221        Self {
222            stub: true,
223            ..Self::default()
224        }
225    }
226
227    /// Add a per-method override and return self (chainable builder).
228    #[must_use]
229    pub fn with_method_override(mut self, method: CrudMethod, ov: MethodOverride) -> Self {
230        self.per_method.insert(method, ov);
231        self
232    }
233
234    /// Resolve the effective shape for one CRUD method, applying
235    /// `per_method` overrides on top of the top-level defaults.
236    #[must_use]
237    pub fn for_method(&self, method: CrudMethod) -> EffectiveShape {
238        let ov = self.per_method.get(&method);
239        EffectiveShape {
240            identifier_field: ov
241                .and_then(|o| o.identifier_field.clone())
242                .unwrap_or_else(|| self.identifier_field.clone()),
243            identifier_pointer: ov
244                .and_then(|o| o.identifier_pointer)
245                .unwrap_or(self.identifier_pointer),
246            body_template: ov.and_then(|o| o.body_template.clone()),
247            body_field_skips: ov
248                .map(|o| o.body_field_skips.clone())
249                .unwrap_or_default(),
250        }
251    }
252
253    /// True when at least one method uses
254    /// [`BodyTemplate::Int64FromExternalName`]. Drives conditional
255    /// `strconv` import in the emitted controller file.
256    #[must_use]
257    pub fn needs_strconv_import(&self) -> bool {
258        self.per_method.values().any(|o| {
259            matches!(
260                o.body_template,
261                Some(BodyTemplate::Int64FromExternalName { .. })
262            )
263        })
264    }
265
266    /// True when at least one method's body construction calls
267    /// `meta.GetExternalName(cr)`. False when every method uses
268    /// `BodyTemplate::NoIdentifier` or `BodyTemplate::SpecFields`
269    /// (neither references meta). Drives conditional `meta` import.
270    #[must_use]
271    pub fn needs_meta_import(&self) -> bool {
272        // Any method without an explicit body_template uses the default
273        // string-identifier path which calls meta.GetExternalName.
274        // Same for Int64FromExternalName.
275        for method in [CrudMethod::Read, CrudMethod::Create, CrudMethod::Update, CrudMethod::Delete] {
276            let eff = self.for_method(method);
277            match eff.body_template {
278                None | Some(BodyTemplate::Int64FromExternalName { .. }) => return true,
279                Some(BodyTemplate::NoIdentifier) | Some(BodyTemplate::SpecFields(_)) => continue,
280            }
281        }
282        false
283    }
284
285    /// True when this method's body construction references `cr`
286    /// (the type-asserted spec). Used by build_*_func to decide
287    /// between `cr, ok :=` (referenced) and `_, ok :=` (discarded).
288    #[must_use]
289    pub fn body_uses_cr(&self, method: CrudMethod) -> bool {
290        let eff = self.for_method(method);
291        match eff.body_template {
292            // NoIdentifier emits just `{Token: &e.token}` — no cr.
293            Some(BodyTemplate::NoIdentifier) => false,
294            // Everything else references cr (default path via
295            // meta.GetExternalName(cr); Int64 same; SpecFields via
296            // cr.Spec.ForProvider.X).
297            _ => true,
298        }
299    }
300}
301
302impl ControllerConfig {
303    #[must_use]
304    pub fn akeyless_default() -> Self {
305        Self {
306            sdk_module: "github.com/pleme-io/akeyless-go".to_string(),
307            provider_module: "github.com/pleme-io/crossplane-akeyless".to_string(),
308            api_group: "akeyless.crossplane.io".to_string(),
309            api_version: "v1alpha1".to_string(),
310            resource_shapes: akeyless_resource_shape_overrides(),
311            body_sigs: None,
312        }
313    }
314
315    /// Look up the shape for a resource, falling back to the default
316    /// (`Name string`) when no override is registered.
317    #[must_use]
318    pub fn shape_for(&self, resource: &IacResource, provider: &IacProvider) -> ResourceShape {
319        let key: &str = strip_provider_prefix(&resource.name, &provider.name);
320        self.resource_shapes
321            .get(key)
322            .cloned()
323            .unwrap_or_default()
324    }
325}
326
327/// Hardcoded shape overrides for the akeyless TOML corpus, derived from
328/// inspecting the actual `pleme-io/akeyless-go` SDK body types
329/// (`api_v2.go` + `model_*.go`). Future iteration can replace the
330/// hardcoded mapping with OpenAPI-introspection at generation time.
331#[must_use]
332fn akeyless_resource_shape_overrides() -> BTreeMap<String, ResourceShape> {
333    let mut m = BTreeMap::new();
334    // Class B-simple: alternate single-string identifier field uniform across CRUD.
335    m.insert("esm".into(), ResourceShape::alt_field("EsmName"));
336    m.insert("usc".into(), ResourceShape::alt_field("UscName"));
337
338    // Class B-graduated (M3.2): per-method overrides.
339    //
340    // certificate: GetCertificateValue.Name *string (only outlier);
341    // CreateCertificate / UpdateCertificateValue / DeleteItem all
342    // have Name string. Default pointer=false; Read overrides to true.
343    m.insert(
344        "certificate".into(),
345        ResourceShape::default().with_method_override(
346            CrudMethod::Read,
347            MethodOverride {
348                identifier_pointer: Some(true),
349                ..Default::default()
350            },
351        ),
352    );
353    // kmip_client: KmipCreateClient.Name string; KmipDescribeClient
354    // and KmipDeleteClient both Name *string. Default pointer=false;
355    // Read + Delete override to true.
356    m.insert(
357        "kmip_client".into(),
358        ResourceShape::default()
359            .with_method_override(
360                CrudMethod::Read,
361                MethodOverride {
362                    identifier_pointer: Some(true),
363                    ..Default::default()
364                },
365            )
366            .with_method_override(
367                CrudMethod::Delete,
368                MethodOverride {
369                    identifier_pointer: Some(true),
370                    ..Default::default()
371                },
372            ),
373    );
374
375    // gateway_migration: Name string default; Read+Update use Name *string,
376    // Delete uses Id string.
377    m.insert(
378        "gateway_migration".into(),
379        ResourceShape::default()
380            .with_method_override(
381                CrudMethod::Read,
382                MethodOverride {
383                    identifier_pointer: Some(true),
384                    ..Default::default()
385                },
386            )
387            .with_method_override(
388                CrudMethod::Update,
389                MethodOverride {
390                    identifier_pointer: Some(true),
391                    ..Default::default()
392                },
393            )
394            .with_method_override(
395                CrudMethod::Delete,
396                MethodOverride {
397                    identifier_field: Some("Id".to_string()),
398                    identifier_pointer: Some(false),
399                    ..Default::default()
400                },
401            ),
402    );
403
404    // policy: 3-of-4 use Id string (Read, Update, Delete); Create uses
405    // Path string. Default to Id; Create overrides to Path.
406    m.insert(
407        "policy".into(),
408        ResourceShape {
409            identifier_field: "Id".to_string(),
410            ..ResourceShape::default()
411        }
412        .with_method_override(
413            CrudMethod::Create,
414            MethodOverride {
415                identifier_field: Some("Path".to_string()),
416                ..Default::default()
417            },
418        ),
419    );
420
421    // kmip_environment: Read+Delete have no identifier (singleton bodies).
422    // Create uses Hostname (alt-field).
423    m.insert(
424        "kmip_environment".into(),
425        ResourceShape::default()
426            .with_method_override(
427                CrudMethod::Read,
428                MethodOverride {
429                    body_template: Some(BodyTemplate::NoIdentifier),
430                    ..Default::default()
431                },
432            )
433            .with_method_override(
434                CrudMethod::Create,
435                MethodOverride {
436                    identifier_field: Some("Hostname".to_string()),
437                    ..Default::default()
438                },
439            )
440            .with_method_override(
441                CrudMethod::Delete,
442                MethodOverride {
443                    body_template: Some(BodyTemplate::NoIdentifier),
444                    ..Default::default()
445                },
446            ),
447    );
448
449    // kmip_client_v2: same shape as kmip_client — KmipCreateClient.Name
450    // string; KmipDescribeClient and KmipDeleteClient both Name *string.
451    // Missing entry caused a real E0308 (pointer/value mismatch) build
452    // failure, 2026-07-10 — a distinct TOML resource from kmip_client
453    // (v1), not a stale duplicate.
454    m.insert(
455        "kmip_client_v2".into(),
456        ResourceShape::default()
457            .with_method_override(
458                CrudMethod::Read,
459                MethodOverride {
460                    identifier_pointer: Some(true),
461                    ..Default::default()
462                },
463            )
464            .with_method_override(
465                CrudMethod::Delete,
466                MethodOverride {
467                    identifier_pointer: Some(true),
468                    ..Default::default()
469                },
470            ),
471    );
472
473    // kmip_environment_v2: same shape as kmip_environment — Read
474    // (KmipDescribeServer) and Delete (KmipDeleteServer) have no
475    // identifier field at all; Create (KmipServerSetup) uses Hostname.
476    // Missing entry caused a real E0559 (unknown field Name) build
477    // failure, 2026-07-10.
478    m.insert(
479        "kmip_environment_v2".into(),
480        ResourceShape::default()
481            .with_method_override(
482                CrudMethod::Read,
483                MethodOverride {
484                    body_template: Some(BodyTemplate::NoIdentifier),
485                    ..Default::default()
486                },
487            )
488            .with_method_override(
489                CrudMethod::Create,
490                MethodOverride {
491                    identifier_field: Some("Hostname".to_string()),
492                    ..Default::default()
493                },
494            )
495            .with_method_override(
496                CrudMethod::Delete,
497                MethodOverride {
498                    body_template: Some(BodyTemplate::NoIdentifier),
499                    ..Default::default()
500                },
501            ),
502    );
503
504    // gateway_log_forwarding_*: 11 near-identical singleton config
505    // resources (aws_s3/azure_analytics/datadog/elasticsearch/
506    // google_chronicle/logstash/logz_io/splunk/stdout/sumologic/syslog).
507    // Confirmed against the akeyless-go SDK: GatewayGetLogForwarding
508    // {Json,Token,UidToken} and every GatewayUpdateLogForwarding<X>
509    // variant (used for Create/Update/Delete alike — the OpenAPI exposes
510    // only an upsert endpoint, no separate create/delete; the resource
511    // TOML's own header comment names this) carry NO identifier field
512    // whatsoever, not even an alt-field — a genuine singleton, unlike
513    // kmip_environment which at least has Hostname on Create. All four
514    // CRUD methods use NoIdentifier. Missing entries caused real
515    // E0559 (unknown field Name) build failures across all 11, 2026-07-10.
516    let log_forwarding_shape = || {
517        ResourceShape::default()
518            .with_method_override(
519                CrudMethod::Read,
520                MethodOverride {
521                    body_template: Some(BodyTemplate::NoIdentifier),
522                    ..Default::default()
523                },
524            )
525            .with_method_override(
526                CrudMethod::Create,
527                MethodOverride {
528                    body_template: Some(BodyTemplate::NoIdentifier),
529                    ..Default::default()
530                },
531            )
532            .with_method_override(
533                CrudMethod::Update,
534                MethodOverride {
535                    body_template: Some(BodyTemplate::NoIdentifier),
536                    ..Default::default()
537                },
538            )
539            .with_method_override(
540                CrudMethod::Delete,
541                MethodOverride {
542                    body_template: Some(BodyTemplate::NoIdentifier),
543                    ..Default::default()
544                },
545            )
546    };
547    for suffix in [
548        "aws_s3",
549        "azure_analytics",
550        "datadog",
551        "elasticsearch",
552        "google_chronicle",
553        "logstash",
554        "logz_io",
555        "splunk",
556        "stdout",
557        "sumologic",
558        "syslog",
559    ] {
560        m.insert(
561            format!("gateway_log_forwarding_{suffix}"),
562            log_forwarding_shape(),
563        );
564    }
565
566    // account_custom_field: Read/Update/Delete bodies use Id int64;
567    // Create uses Name string.
568    let int64_id = || MethodOverride {
569        body_template: Some(BodyTemplate::Int64FromExternalName {
570            field: "Id".to_string(),
571        }),
572        ..Default::default()
573    };
574    m.insert(
575        "account_custom_field".into(),
576        ResourceShape::default()
577            .with_method_override(CrudMethod::Read, int64_id())
578            .with_method_override(CrudMethod::Update, int64_id())
579            .with_method_override(CrudMethod::Delete, int64_id()),
580    );
581
582    // role_rule: composite (RoleName + Path) on all four methods.
583    // Read uses GetRole which only needs the role name.
584    let role_rule_set_fields = vec![
585        SpecFieldMapping {
586            body_field: "RoleName".to_string(),
587            spec_field: "RoleName".to_string(),
588            pointer: false,
589        },
590        SpecFieldMapping {
591            body_field: "Path".to_string(),
592            spec_field: "Path".to_string(),
593            pointer: false,
594        },
595    ];
596    m.insert(
597        "role_rule".into(),
598        ResourceShape::default()
599            .with_method_override(
600                CrudMethod::Read,
601                MethodOverride {
602                    body_template: Some(BodyTemplate::SpecFields(vec![SpecFieldMapping {
603                        body_field: "Name".to_string(),
604                        spec_field: "RoleName".to_string(),
605                        pointer: false,
606                    }])),
607                    ..Default::default()
608                },
609            )
610            .with_method_override(
611                CrudMethod::Create,
612                MethodOverride {
613                    body_template: Some(BodyTemplate::SpecFields(role_rule_set_fields.clone())),
614                    ..Default::default()
615                },
616            )
617            .with_method_override(
618                CrudMethod::Update,
619                MethodOverride {
620                    body_template: Some(BodyTemplate::SpecFields(role_rule_set_fields.clone())),
621                    ..Default::default()
622                },
623            )
624            .with_method_override(
625                CrudMethod::Delete,
626                MethodOverride {
627                    body_template: Some(BodyTemplate::SpecFields(role_rule_set_fields)),
628                    ..Default::default()
629                },
630            ),
631    );
632
633    // role_auth_method_assoc: composite (RoleName + AmName) on Create;
634    // Read uses GetRole (single Name field); Delete uses AssocId (from
635    // external-name, set when Create succeeds).
636    m.insert(
637        "role_auth_method_assoc".into(),
638        ResourceShape::default()
639            .with_method_override(
640                CrudMethod::Read,
641                MethodOverride {
642                    body_template: Some(BodyTemplate::SpecFields(vec![SpecFieldMapping {
643                        body_field: "Name".to_string(),
644                        spec_field: "RoleName".to_string(),
645                        pointer: false,
646                    }])),
647                    ..Default::default()
648                },
649            )
650            .with_method_override(
651                CrudMethod::Create,
652                MethodOverride {
653                    body_template: Some(BodyTemplate::SpecFields(vec![
654                        SpecFieldMapping {
655                            body_field: "RoleName".to_string(),
656                            spec_field: "RoleName".to_string(),
657                            pointer: false,
658                        },
659                        SpecFieldMapping {
660                            body_field: "AmName".to_string(),
661                            spec_field: "AmName".to_string(),
662                            pointer: false,
663                        },
664                    ])),
665                    ..Default::default()
666                },
667            )
668            .with_method_override(
669                CrudMethod::Delete,
670                MethodOverride {
671                    identifier_field: Some("AssocId".to_string()),
672                    ..Default::default()
673                },
674            ),
675    );
676
677    // M6.2 broad-walk per-resource skip overrides — for resources where
678    // the akeyless TOML's IacType disagrees with the akeyless-go SDK
679    // body's Go type for a given field. Each entry below was derived
680    // from `go build ./...` failures observed against the regenerated
681    // crossplane-akeyless tree on 2026-05-07. M6.4 (schema-driven
682    // filtering) replaces this hardcoded list by reading the SDK body
683    // schema from the OpenAPI spec at emit time.
684    let skip_create_update = |skips: Vec<String>| {
685        ResourceShape::default()
686            .with_method_override(
687                CrudMethod::Create,
688                MethodOverride {
689                    body_field_skips: skips.clone(),
690                    ..Default::default()
691                },
692            )
693            .with_method_override(
694                CrudMethod::Update,
695                MethodOverride {
696                    body_field_skips: skips,
697                    ..Default::default()
698                },
699            )
700    };
701    // sshcertissuer: DeleteProtection is *bool in Parameters but *string
702    // in CreateSSHCertIssuer / UpdateSSHCertIssuer body schemas.
703    m.insert(
704        "ssh_cert_issuer".into(),
705        skip_create_update(vec!["DeleteProtection".to_string()]),
706    );
707    // targetwindows: UseTls is *bool in Parameters but *string in the
708    // TargetCreateWindows / TargetUpdateWindows body schemas.
709    m.insert(
710        "target_windows".into(),
711        skip_create_update(vec!["UseTls".to_string()]),
712    );
713    // rotatedsecretwindows: DeleteProtection bool/string mismatch +
714    // RotationHour int64/int32 mismatch + Update body lacks TargetName.
715    m.insert(
716        "rotated_secret_windows".into(),
717        ResourceShape::default()
718            .with_method_override(
719                CrudMethod::Create,
720                MethodOverride {
721                    body_field_skips: vec![
722                        "DeleteProtection".to_string(),
723                        "RotationHour".to_string(),
724                    ],
725                    ..Default::default()
726                },
727            )
728            .with_method_override(
729                CrudMethod::Update,
730                MethodOverride {
731                    body_field_skips: vec![
732                        "DeleteProtection".to_string(),
733                        "RotationHour".to_string(),
734                        "TargetName".to_string(),
735                    ],
736                    ..Default::default()
737                },
738            ),
739    );
740    // usc: Update body (UscUpdate) lacks ObjectType / Region / SecretName
741    // — those exist only on UscCreate. Inherit the alt_field("UscName")
742    // identifier and skip on Update.
743    m.insert(
744        "usc".into(),
745        ResourceShape::alt_field("UscName").with_method_override(
746            CrudMethod::Update,
747            MethodOverride {
748                body_field_skips: vec![
749                    "ObjectType".to_string(),
750                    "Region".to_string(),
751                    "SecretName".to_string(),
752                ],
753                ..Default::default()
754            },
755        ),
756    );
757    m
758}
759
760/// Render the per-resource controller .go file.
761#[must_use]
762pub fn render_controller(
763    resource: &IacResource,
764    provider: &IacProvider,
765    config: &ControllerConfig,
766) -> String {
767    print_file(&build_controller_file(resource, provider, config))
768}
769
770// ── AST construction ──────────────────────────────────────────────────────
771
772#[must_use]
773pub fn build_controller_file(
774    resource: &IacResource,
775    provider: &IacProvider,
776    config: &ControllerConfig,
777) -> GoFile {
778    let kind = cr_kind(resource, provider);
779    let pkg = package_name(resource, provider);
780    let shape = config.shape_for(resource, provider);
781
782    let mut file = GoFile::new(&pkg);
783
784    // Imports — stdlib first (printer groups), then third-party with aliases.
785    file.imports.push(GoImport::plain("context"));
786    if !shape.stub {
787        file.imports.push(GoImport::plain("encoding/json"));
788    }
789    file.imports.push(GoImport::plain("errors"));
790    if !shape.stub {
791        file.imports.push(GoImport::plain("fmt"));
792        file.imports.push(GoImport::plain("net/http"));
793    }
794    if shape.needs_strconv_import() {
795        file.imports.push(GoImport::plain("strconv"));
796    }
797    file.imports.push(GoImport::plain("time"));
798    let _ = shape.needs_meta_import(); // referenced below in conditional import block
799    // xpv1 (xpv1.Available) and meta (meta.GetExternalName) are only
800    // referenced by non-stub Observe/Create/Update/Delete bodies.
801    // Skip them when the controller is fully stubbed to avoid Go's
802    // "imported and not used" error.
803    if !shape.stub {
804        file.imports.push(GoImport::aliased(
805            "xpv1",
806            "github.com/crossplane/crossplane-runtime/apis/common/v1",
807        ));
808        if shape.needs_meta_import() {
809            file.imports.push(GoImport::plain(
810                "github.com/crossplane/crossplane-runtime/pkg/meta",
811            ));
812        }
813    }
814    file.imports.push(GoImport::plain(
815        "github.com/crossplane/crossplane-runtime/pkg/logging",
816    ));
817    file.imports.push(GoImport::plain(
818        "github.com/crossplane/crossplane-runtime/pkg/reconciler/managed",
819    ));
820    file.imports.push(GoImport::plain(
821        "github.com/crossplane/crossplane-runtime/pkg/resource",
822    ));
823    file.imports.push(GoImport::aliased(
824        "ctrl",
825        "sigs.k8s.io/controller-runtime",
826    ));
827    file.imports.push(GoImport::plain(
828        "sigs.k8s.io/controller-runtime/pkg/client",
829    ));
830    file.imports.push(GoImport::aliased("akeyless", &config.sdk_module));
831    file.imports.push(GoImport::aliased(
832        "v1alpha1",
833        &format!("{}/apis/{}/v1alpha1", config.provider_module, pkg),
834    ));
835    let provider_pkg = provider.name.replace('-', "");
836    file.imports.push(GoImport::aliased(
837        "providerv1alpha1",
838        &format!(
839            "{}/apis/{}/v1alpha1",
840            config.provider_module, provider_pkg
841        ),
842    ));
843
844    // type akeylessCredentials struct { ... json tags ... } — used by Connect to
845    // decode the credential blob coming from the ProviderConfig's referenced Secret.
846    if !shape.stub {
847        file.decls
848            .push(GoDecl::Type(build_credentials_struct_type()));
849    }
850    // type external struct { client *akeyless.APIClient ; token string }
851    file.decls
852        .push(GoDecl::Type(build_external_struct_type()));
853
854    // Setup function
855    file.decls.push(GoDecl::Func(build_setup_func(&kind)));
856
857    // type connector struct { kube client.Client }
858    file.decls.push(GoDecl::Type(build_connector_struct_type()));
859
860    // (c *connector) Connect(...) (managed.ExternalClient, error)
861    file.decls.push(GoDecl::Func(build_connect_func(&kind)));
862
863    // (e *external) Observe / Create / Update / Delete
864    file.decls.push(GoDecl::Func(build_observe_func(
865        resource,
866        &kind,
867        &shape,
868        &config.body_sigs,
869    )));
870    file.decls.push(GoDecl::Func(build_create_func(
871        resource,
872        &kind,
873        &shape,
874        &config.body_sigs,
875    )));
876    file.decls.push(GoDecl::Func(build_update_func(
877        resource,
878        &kind,
879        &shape,
880        &config.body_sigs,
881    )));
882    file.decls.push(GoDecl::Func(build_delete_func(
883        resource,
884        &kind,
885        &shape,
886        &config.body_sigs,
887    )));
888    file.decls.push(GoDecl::Func(build_disconnect_func()));
889
890    file
891}
892
893/// Build the body-construction prelude + composite. Dispatches on
894/// the effective shape's `body_template`:
895///
896///   - `Some(NoIdentifier)`         → empty body except `Token`
897///   - `Some(Int64FromExternalName)` → strconv parse + int64 field
898///   - `Some(SpecFields)`           → multi-field from cr.Spec.ForProvider
899///   - `None`                       → default string-identifier path
900///                                     (uses identifier_field +
901///                                     identifier_pointer)
902///
903/// M6.2 — Create/Update default-branch bodies additionally walk
904/// `resource.attributes` and push every non-computed non-identifier
905/// scalar field as `BodyField: cr.Spec.ForProvider.BodyField`. Read +
906/// Delete keep the identifier-only shape because akeyless's GET/DELETE
907/// body schemas don't carry the Parameters fields. Pointer-ness on
908/// pushed fields matches the Parameters struct (same TOML-driven
909/// required/optional flag drives both the Parameters emit in
910/// `types_gen` AND the SDK body schema in `akeyless-go`), so we can
911/// pass the field reference directly without addr-of/deref tricks.
912fn build_request_body(
913    body_type: &str,
914    shape: &ResourceShape,
915    method: CrudMethod,
916    resource: &IacResource,
917    body_sigs: &SharedBodySigMap,
918) -> (Vec<GoStmt>, GoExpr) {
919    let eff = shape.for_method(method);
920    if let Some(template) = eff.body_template.as_ref() {
921        return build_body_from_template(body_type, template);
922    }
923    let id_value = if eff.identifier_pointer {
924        GoExpr::AddressOf(Box::new(GoExpr::ident("name")))
925    } else {
926        GoExpr::call(
927            GoExpr::path(&["meta", "GetExternalName"]),
928            vec![GoExpr::ident("cr")],
929        )
930    };
931    let preamble = if eff.identifier_pointer {
932        vec![GoStmt::ShortDecl {
933            names: vec!["name".to_string()],
934            values: vec![GoExpr::call(
935                GoExpr::path(&["meta", "GetExternalName"]),
936                vec![GoExpr::ident("cr")],
937            )],
938        }]
939    } else {
940        vec![]
941    };
942    let mut fields: Vec<(Option<String>, GoExpr)> = vec![
943        (Some(eff.identifier_field.clone()), id_value),
944        (
945            Some("Token".to_string()),
946            GoExpr::AddressOf(Box::new(GoExpr::sel(
947                GoExpr::ident("e"),
948                "token",
949            ))),
950        ),
951    ];
952    // M6.2 broad walk: push every non-computed non-identifier scalar
953    // attribute as `Pascal: cr.Spec.ForProvider.Pascal` onto the SDK
954    // body composite. Read+Delete bodies stay identifier-only because
955    // the SDK GET/DELETE schemas don't carry the Parameters fields.
956    //
957    // Gating order:
958    //   1. body_sigs is Some       → schema-driven walk (M6.4): walk
959    //                                 unconditionally + filter by SDK
960    //                                 body schema name+type match.
961    //   2. body_sigs is None +     → manual opt-in (M6.2): walk
962    //      shape.push_for_provider   without sig check; resource sets
963    //                                 the flag only when its TOML+SDK
964    //                                 align cleanly.
965    //   3. otherwise               → identifier+token only.
966    let want_walk = matches!(method, CrudMethod::Create | CrudMethod::Update)
967        && (body_sigs.is_some() || shape.push_for_provider_fields);
968    if want_walk {
969        for attr in &resource.attributes {
970            if attr.computed {
971                continue;
972            }
973            if attr.canonical_name == "token" {
974                continue;
975            }
976            let pascal = pascal_case_field(&attr.canonical_name);
977            if pascal == eff.identifier_field {
978                continue;
979            }
980            // Per-resource per-method skip list (legacy from M6.2's
981            // hardcoded-skip phase). Honored even under sig-driven
982            // mode for any pathological case.
983            if eff.body_field_skips.iter().any(|s| s == &pascal) {
984                continue;
985            }
986            // Scalar types only — types_gen collapses List/Map/Object
987            // to opaque `string`. Slice 2 of types_gen relaxes this.
988            if !matches!(
989                attr.iac_type,
990                IacType::String | IacType::Integer | IacType::Float | IacType::Numeric | IacType::Boolean
991            ) {
992                continue;
993            }
994            // M6.4 — schema-driven filter: skip when the SDK body
995            // schema lacks this field OR its name+type/required-ness
996            // disagrees with the IacAttribute. Restores 100% coverage
997            // across the corpus regardless of TOML/SDK divergences.
998            if let Some(sigs) = body_sigs.as_ref()
999                && sigs.check_field(body_type, &pascal, &attr.iac_type, attr.required)
1000                    == FieldMatch::Skip
1001            {
1002                continue;
1003            }
1004            fields.push((
1005                Some(pascal.clone()),
1006                GoExpr::path(&["cr", "Spec", "ForProvider", &pascal]),
1007            ));
1008        }
1009    }
1010    let composite = GoExpr::Composite {
1011        ty: GoType::qualified("akeyless", body_type),
1012        fields,
1013        addr_of: false,
1014    };
1015    (preamble, composite)
1016}
1017
1018fn pascal_case_field(canonical: &str) -> String {
1019    iac_forge::naming::to_pascal_case(&iac_forge::naming::to_snake_case(canonical))
1020}
1021
1022fn build_body_from_template(body_type: &str, template: &BodyTemplate) -> (Vec<GoStmt>, GoExpr) {
1023    match template {
1024        BodyTemplate::NoIdentifier => {
1025            let composite = GoExpr::Composite {
1026                ty: GoType::qualified("akeyless", body_type),
1027                fields: vec![(
1028                    Some("Token".to_string()),
1029                    GoExpr::AddressOf(Box::new(GoExpr::sel(
1030                        GoExpr::ident("e"),
1031                        "token",
1032                    ))),
1033                )],
1034                addr_of: false,
1035            };
1036            (vec![], composite)
1037        }
1038        BodyTemplate::Int64FromExternalName { field } => {
1039            // id, _ := strconv.ParseInt(meta.GetExternalName(cr), 10, 64)
1040            let preamble = vec![GoStmt::ShortDecl {
1041                names: vec!["id".to_string(), "_".to_string()],
1042                values: vec![GoExpr::call(
1043                    GoExpr::path(&["strconv", "ParseInt"]),
1044                    vec![
1045                        GoExpr::call(
1046                            GoExpr::path(&["meta", "GetExternalName"]),
1047                            vec![GoExpr::ident("cr")],
1048                        ),
1049                        GoExpr::Lit(GoLit::Int(10)),
1050                        GoExpr::Lit(GoLit::Int(64)),
1051                    ],
1052                )],
1053            }];
1054            let composite = GoExpr::Composite {
1055                ty: GoType::qualified("akeyless", body_type),
1056                fields: vec![
1057                    (Some(field.clone()), GoExpr::ident("id")),
1058                    (
1059                        Some("Token".to_string()),
1060                        GoExpr::AddressOf(Box::new(GoExpr::sel(
1061                            GoExpr::ident("e"),
1062                            "token",
1063                        ))),
1064                    ),
1065                ],
1066                addr_of: false,
1067            };
1068            (preamble, composite)
1069        }
1070        BodyTemplate::SpecFields(mappings) => {
1071            // body := akeyless.X{Field1: cr.Spec.ForProvider.Spec1, ..., Token: &e.token}
1072            let mut fields: Vec<(Option<String>, GoExpr)> = mappings
1073                .iter()
1074                .map(|m| {
1075                    let value = GoExpr::path(&["cr", "Spec", "ForProvider", m.spec_field.as_str()]);
1076                    let value = if m.pointer {
1077                        GoExpr::AddressOf(Box::new(value))
1078                    } else {
1079                        value
1080                    };
1081                    (Some(m.body_field.clone()), value)
1082                })
1083                .collect();
1084            fields.push((
1085                Some("Token".to_string()),
1086                GoExpr::AddressOf(Box::new(GoExpr::sel(
1087                    GoExpr::ident("e"),
1088                    "token",
1089                ))),
1090            ));
1091            let composite = GoExpr::Composite {
1092                ty: GoType::qualified("akeyless", body_type),
1093                fields,
1094                addr_of: false,
1095            };
1096            (vec![], composite)
1097        }
1098    }
1099}
1100
1101fn build_disconnect_func() -> GoFuncDecl {
1102    // crossplane-runtime v1.18 added Disconnect(ctx) error to the
1103    // ExternalClient interface. The default no-op is correct for any
1104    // SDK that doesn't hold long-lived resources beyond per-call
1105    // request state — the akeyless SDK falls into this category.
1106    let mut body = GoBlock::new();
1107    body.push(GoStmt::Return(vec![GoExpr::nil()]));
1108    GoFuncDecl {
1109        name: "Disconnect".to_string(),
1110        doc: Some(
1111            "Disconnect releases any per-cluster client resources. The akeyless SDK\nholds no long-lived resources beyond per-call request state, so this is\na no-op. Required by crossplane-runtime v1.18+'s ExternalClient interface."
1112                .to_string(),
1113        ),
1114        recv: Some(GoRecv {
1115            name: "_".to_string(),
1116            ty: GoType::pointer(GoType::named("external")),
1117        }),
1118        params: vec![GoParam {
1119            name: "_".to_string(),
1120            ty: GoType::qualified("context", "Context"),
1121        }],
1122        returns: vec![GoType::named("error")],
1123        body,
1124    }
1125}
1126
1127fn build_credentials_struct_type() -> GoTypeDecl {
1128    let mk = |name: &str, json_tag: &str| GoField {
1129        name: Some(name.to_string()),
1130        ty: GoType::named("string"),
1131        doc: None,
1132        markers: vec![],
1133        tags: vec![GoStructTag::Json(JsonTag {
1134            name: json_tag.to_string(),
1135            omitempty: true,
1136            inline: false,
1137        })],
1138    };
1139    let fields = vec![
1140        mk("AccessID", "access_id"),
1141        mk("AccessKey", "access_key"),
1142        mk("AccessIDDash", "access-id"),
1143        mk("AccessKeyDash", "access-key"),
1144    ];
1145    GoTypeDecl {
1146        name: "akeylessCredentials".to_string(),
1147        doc: Some(
1148            "akeylessCredentials is the JSON shape the controller expects from the\nProviderConfig's referenced Secret. Both akeyless's snake_case and the\nakeyless-CLI's hyphenated variants are accepted."
1149                .to_string(),
1150        ),
1151        markers: vec![],
1152        body: GoTypeBody::Struct(fields),
1153    }
1154}
1155
1156fn build_external_struct_type() -> GoTypeDecl {
1157    let fields = vec![
1158        GoField {
1159            name: Some("client".to_string()),
1160            ty: GoType::pointer(GoType::qualified("akeyless", "APIClient")),
1161            doc: None,
1162            markers: vec![],
1163            tags: vec![],
1164        },
1165        GoField {
1166            name: Some("token".to_string()),
1167            ty: GoType::named("string"),
1168            doc: None,
1169            markers: vec![],
1170            tags: vec![],
1171        },
1172    ];
1173    GoTypeDecl {
1174        name: "external".to_string(),
1175        doc: Some(
1176            "external is the per-cluster reconciler that owns the SDK client and\nthe token resolved from the bound ProviderConfig."
1177                .to_string(),
1178        ),
1179        markers: vec![],
1180        body: GoTypeBody::Struct(fields),
1181    }
1182}
1183
1184fn build_connector_struct_type() -> GoTypeDecl {
1185    let fields = vec![GoField {
1186        name: Some("kube".to_string()),
1187        ty: GoType::qualified("client", "Client"),
1188        doc: None,
1189        markers: vec![],
1190        tags: vec![],
1191    }];
1192    GoTypeDecl {
1193        name: "connector".to_string(),
1194        doc: Some(
1195            "connector resolves a ProviderConfig and constructs an external\nclient for each managed-resource reconcile loop."
1196                .to_string(),
1197        ),
1198        markers: vec![],
1199        body: GoTypeBody::Struct(fields),
1200    }
1201}
1202
1203fn build_setup_func(kind: &str) -> GoFuncDecl {
1204    let mut body = GoBlock::new();
1205    // name := "<Kind>"
1206    body.push(GoStmt::ShortDecl {
1207        names: vec!["name".to_string()],
1208        values: vec![GoExpr::str(kind)],
1209    });
1210    // gvk := v1alpha1.GroupVersion.WithKind("<Kind>")
1211    body.push(GoStmt::ShortDecl {
1212        names: vec!["gvk".to_string()],
1213        values: vec![GoExpr::call(
1214            GoExpr::sel(
1215                GoExpr::sel(GoExpr::ident("v1alpha1"), "GroupVersion"),
1216                "WithKind",
1217            ),
1218            vec![GoExpr::str(kind)],
1219        )],
1220    });
1221    // r := managed.NewReconciler(mgr,
1222    //         resource.ManagedKind(gvk),
1223    //         managed.WithExternalConnecter(&connector{kube: mgr.GetClient()}),
1224    //         managed.WithPollInterval(pollInterval),
1225    //         managed.WithLogger(ctrl.Log.WithName(name)))
1226    let connector_lit = GoExpr::Composite {
1227        ty: GoType::named("connector"),
1228        fields: vec![(
1229            Some("kube".to_string()),
1230            GoExpr::call(
1231                GoExpr::sel(GoExpr::ident("mgr"), "GetClient"),
1232                vec![],
1233            ),
1234        )],
1235        addr_of: true,
1236    };
1237    let new_reconciler = GoExpr::call(
1238        GoExpr::path(&["managed", "NewReconciler"]),
1239        vec![
1240            GoExpr::ident("mgr"),
1241            GoExpr::call(
1242                GoExpr::path(&["resource", "ManagedKind"]),
1243                vec![GoExpr::ident("gvk")],
1244            ),
1245            GoExpr::call(
1246                GoExpr::path(&["managed", "WithExternalConnecter"]),
1247                vec![connector_lit],
1248            ),
1249            GoExpr::call(
1250                GoExpr::path(&["managed", "WithPollInterval"]),
1251                vec![GoExpr::ident("pollInterval")],
1252            ),
1253            GoExpr::call(
1254                GoExpr::path(&["managed", "WithLogger"]),
1255                vec![GoExpr::call(
1256                    GoExpr::path(&["logging", "NewLogrLogger"]),
1257                    vec![GoExpr::call(
1258                        GoExpr::path(&["ctrl", "Log", "WithName"]),
1259                        vec![GoExpr::ident("name")],
1260                    )],
1261                )],
1262            ),
1263        ],
1264    );
1265    body.push(GoStmt::ShortDecl {
1266        names: vec!["r".to_string()],
1267        values: vec![new_reconciler],
1268    });
1269    // return ctrl.NewControllerManagedBy(mgr).Named(name).For(&v1alpha1.<Kind>{}).Complete(r)
1270    let chain = GoExpr::call(
1271        GoExpr::sel(
1272            GoExpr::call(
1273                GoExpr::sel(
1274                    GoExpr::call(
1275                        GoExpr::sel(
1276                            GoExpr::call(
1277                                GoExpr::path(&["ctrl", "NewControllerManagedBy"]),
1278                                vec![GoExpr::ident("mgr")],
1279                            ),
1280                            "Named",
1281                        ),
1282                        vec![GoExpr::ident("name")],
1283                    ),
1284                    "For",
1285                ),
1286                vec![GoExpr::Composite {
1287                    ty: GoType::qualified("v1alpha1", kind),
1288                    fields: vec![],
1289                    addr_of: true,
1290                }],
1291            ),
1292            "Complete",
1293        ),
1294        vec![GoExpr::ident("r")],
1295    );
1296    body.push(GoStmt::Return(vec![chain]));
1297
1298    GoFuncDecl {
1299        name: "Setup".to_string(),
1300        doc: Some("Setup wires this resource's controller into the manager.".to_string()),
1301        recv: None,
1302        params: vec![
1303            GoParam {
1304                name: "mgr".to_string(),
1305                ty: GoType::qualified("ctrl", "Manager"),
1306            },
1307            GoParam {
1308                name: "pollInterval".to_string(),
1309                ty: GoType::qualified("time", "Duration"),
1310            },
1311        ],
1312        returns: vec![GoType::named("error")],
1313        body,
1314    }
1315}
1316
1317fn build_connect_func(kind: &str) -> GoFuncDecl {
1318    let mut body = GoBlock::new();
1319    // cr, ok := mg.(*v1alpha1.<Kind>)
1320    body.push(GoStmt::ShortDecl {
1321        names: vec!["cr".to_string(), "ok".to_string()],
1322        values: vec![GoExpr::TypeAssert {
1323            x: Box::new(GoExpr::ident("mg")),
1324            ty: GoType::pointer(GoType::qualified("v1alpha1", kind)),
1325            with_ok: true,
1326        }],
1327    });
1328    // if !ok { return nil, errors.New("expected *v1alpha1.<Kind>") }
1329    body.push(GoStmt::If {
1330        init: None,
1331        cond: GoExpr::ident("!ok"),
1332        body: {
1333            let mut b = GoBlock::new();
1334            b.push(GoStmt::Return(vec![
1335                GoExpr::nil(),
1336                GoExpr::call(
1337                    GoExpr::path(&["errors", "New"]),
1338                    vec![GoExpr::str(&format!("expected *v1alpha1.{kind}"))],
1339                ),
1340            ]));
1341            b
1342        },
1343        else_body: None,
1344    });
1345    // pcRef := cr.GetProviderConfigReference()
1346    body.push(GoStmt::ShortDecl {
1347        names: vec!["pcRef".to_string()],
1348        values: vec![GoExpr::call(
1349            GoExpr::sel(GoExpr::ident("cr"), "GetProviderConfigReference"),
1350            vec![],
1351        )],
1352    });
1353    // if pcRef == nil { return nil, errors.New("no provider config reference") }
1354    body.push(GoStmt::If {
1355        init: None,
1356        cond: GoExpr::ident("pcRef == nil"),
1357        body: {
1358            let mut b = GoBlock::new();
1359            b.push(GoStmt::Return(vec![
1360                GoExpr::nil(),
1361                GoExpr::call(
1362                    GoExpr::path(&["errors", "New"]),
1363                    vec![GoExpr::str("no provider config reference")],
1364                ),
1365            ]));
1366            b
1367        },
1368        else_body: None,
1369    });
1370    body.push(GoStmt::Blank);
1371    // pc := &providerv1alpha1.ProviderConfig{}
1372    body.push(GoStmt::ShortDecl {
1373        names: vec!["pc".to_string()],
1374        values: vec![GoExpr::Composite {
1375            ty: GoType::qualified("providerv1alpha1", "ProviderConfig"),
1376            fields: vec![],
1377            addr_of: true,
1378        }],
1379    });
1380    // if err := c.kube.Get(ctx, client.ObjectKey{Name: pcRef.Name}, pc); err != nil { return nil, err }
1381    body.push(GoStmt::If {
1382        init: Some(Box::new(GoStmt::ShortDecl {
1383            names: vec!["err".to_string()],
1384            values: vec![GoExpr::call(
1385                GoExpr::sel(
1386                    GoExpr::sel(GoExpr::ident("c"), "kube"),
1387                    "Get",
1388                ),
1389                vec![
1390                    GoExpr::ident("ctx"),
1391                    GoExpr::Composite {
1392                        ty: GoType::qualified("client", "ObjectKey"),
1393                        fields: vec![(
1394                            Some("Name".to_string()),
1395                            GoExpr::sel(GoExpr::ident("pcRef"), "Name"),
1396                        )],
1397                        addr_of: false,
1398                    },
1399                    GoExpr::ident("pc"),
1400                ],
1401            )],
1402        })),
1403        cond: GoExpr::ident("err != nil"),
1404        body: {
1405            let mut b = GoBlock::new();
1406            b.push(GoStmt::Return(vec![GoExpr::nil(), GoExpr::ident("err")]));
1407            b
1408        },
1409        else_body: None,
1410    });
1411    // creds, err := resource.CommonCredentialExtractor(ctx, pc.Spec.Credentials.Source, c.kube, pc.Spec.Credentials.CommonCredentialSelectors)
1412    body.push(GoStmt::ShortDecl {
1413        names: vec!["creds".to_string(), "err".to_string()],
1414        values: vec![GoExpr::call(
1415            GoExpr::path(&["resource", "CommonCredentialExtractor"]),
1416            vec![
1417                GoExpr::ident("ctx"),
1418                GoExpr::path(&["pc", "Spec", "Credentials", "Source"]),
1419                GoExpr::sel(GoExpr::ident("c"), "kube"),
1420                GoExpr::path(&["pc", "Spec", "Credentials", "CommonCredentialSelectors"]),
1421            ],
1422        )],
1423    });
1424    // if err != nil { return nil, err }
1425    body.push(GoStmt::If {
1426        init: None,
1427        cond: GoExpr::ident("err != nil"),
1428        body: {
1429            let mut b = GoBlock::new();
1430            b.push(GoStmt::Return(vec![GoExpr::nil(), GoExpr::ident("err")]));
1431            b
1432        },
1433        else_body: None,
1434    });
1435    body.push(GoStmt::Blank);
1436    // cfg := akeyless.NewConfiguration()
1437    body.push(GoStmt::ShortDecl {
1438        names: vec!["cfg".to_string()],
1439        values: vec![GoExpr::call(
1440            GoExpr::path(&["akeyless", "NewConfiguration"]),
1441            vec![],
1442        )],
1443    });
1444    // if pc.Spec.APIGateway != "" { cfg.Servers = []akeyless.ServerConfiguration{{URL: pc.Spec.APIGateway}} }
1445    body.push(GoStmt::If {
1446        init: None,
1447        cond: GoExpr::ident("pc.Spec.APIGateway != \"\""),
1448        body: {
1449            let mut b = GoBlock::new();
1450            // Slice 1: keep this assignment shape simple — emit a comment
1451            // pointing at slice 2 for slice-literal AST. The goast AST
1452            // doesn't yet have a SliceLit variant; for now we emit a
1453            // Free identifier covering the line.
1454            b.push(GoStmt::Comment(
1455                "TODO goast-slice-2: emit cfg.Servers via structured SliceLit".to_string(),
1456            ));
1457            b.push(GoStmt::Expr(GoExpr::ident(
1458                "cfg.Servers = []akeyless.ServerConfiguration{{URL: pc.Spec.APIGateway}}",
1459            )));
1460            b
1461        },
1462        else_body: None,
1463    });
1464    let _ = creds_unused();
1465    // Decode the credential blob.
1466    //
1467    // Akeyless auth requires BOTH access_id AND access_key — only the
1468    // access_id is identifying; the access_key is the secret. The SDK's
1469    // `token` field expects a session token returned by /auth, NOT the
1470    // raw access_key. We therefore parse `creds` as JSON carrying both
1471    // fields, accepting either snake_case or akeyless-CLI-style hyphens:
1472    //   {"access_id":"p-…","access_key":"…"}
1473    //   {"access-id":"p-…","access-key":"…"}
1474    body.push(GoStmt::Blank);
1475    body.push(GoStmt::Comment(
1476        "Decode the access-id + access-key from the credentials Secret.".to_string(),
1477    ));
1478    body.push(GoStmt::Comment(
1479        "Both keys are required: /auth exchanges them for a session token.".to_string(),
1480    ));
1481    body.push(GoStmt::ShortDecl {
1482        names: vec!["akCreds".to_string()],
1483        values: vec![GoExpr::Composite {
1484            ty: GoType::named("akeylessCredentials"),
1485            fields: vec![],
1486            addr_of: false,
1487        }],
1488    });
1489    body.push(GoStmt::If {
1490        init: Some(Box::new(GoStmt::ShortDecl {
1491            names: vec!["err".to_string()],
1492            values: vec![GoExpr::call(
1493                GoExpr::path(&["json", "Unmarshal"]),
1494                vec![
1495                    GoExpr::ident("creds"),
1496                    GoExpr::AddressOf(Box::new(GoExpr::ident("akCreds"))),
1497                ],
1498            )],
1499        })),
1500        cond: GoExpr::ident("err != nil"),
1501        body: {
1502            let mut b = GoBlock::new();
1503            b.push(GoStmt::Return(vec![
1504                GoExpr::nil(),
1505                GoExpr::call(
1506                    GoExpr::path(&["fmt", "Errorf"]),
1507                    vec![
1508                        GoExpr::str("akeyless credentials must be JSON {\"access_id\":\"...\",\"access_key\":\"...\"}: %w"),
1509                        GoExpr::ident("err"),
1510                    ],
1511                ),
1512            ]));
1513            b
1514        },
1515        else_body: None,
1516    });
1517    body.push(GoStmt::ShortDecl {
1518        names: vec!["accessID".to_string()],
1519        values: vec![GoExpr::sel(GoExpr::ident("akCreds"), "AccessID")],
1520    });
1521    body.push(GoStmt::If {
1522        init: None,
1523        cond: GoExpr::ident("accessID == \"\""),
1524        body: {
1525            let mut b = GoBlock::new();
1526            b.push(GoStmt::Expr(GoExpr::ident(
1527                "accessID = akCreds.AccessIDDash",
1528            )));
1529            b
1530        },
1531        else_body: None,
1532    });
1533    body.push(GoStmt::ShortDecl {
1534        names: vec!["accessKey".to_string()],
1535        values: vec![GoExpr::sel(GoExpr::ident("akCreds"), "AccessKey")],
1536    });
1537    body.push(GoStmt::If {
1538        init: None,
1539        cond: GoExpr::ident("accessKey == \"\""),
1540        body: {
1541            let mut b = GoBlock::new();
1542            b.push(GoStmt::Expr(GoExpr::ident(
1543                "accessKey = akCreds.AccessKeyDash",
1544            )));
1545            b
1546        },
1547        else_body: None,
1548    });
1549    body.push(GoStmt::If {
1550        init: None,
1551        cond: GoExpr::ident("accessID == \"\" || accessKey == \"\""),
1552        body: {
1553            let mut b = GoBlock::new();
1554            b.push(GoStmt::Return(vec![
1555                GoExpr::nil(),
1556                GoExpr::call(
1557                    GoExpr::path(&["errors", "New"]),
1558                    vec![GoExpr::str(
1559                        "akeyless credentials missing access_id or access_key",
1560                    )],
1561                ),
1562            ]));
1563            b
1564        },
1565        else_body: None,
1566    });
1567    body.push(GoStmt::Blank);
1568    // client := akeyless.NewAPIClient(cfg)
1569    body.push(GoStmt::ShortDecl {
1570        names: vec!["apiClient".to_string()],
1571        values: vec![GoExpr::call(
1572            GoExpr::path(&["akeyless", "NewAPIClient"]),
1573            vec![GoExpr::ident("cfg")],
1574        )],
1575    });
1576    // accessType := "access_key"  (declared as var so &accessType is well-typed)
1577    body.push(GoStmt::ShortDecl {
1578        names: vec!["accessType".to_string()],
1579        values: vec![GoExpr::str("access_key")],
1580    });
1581    // authOut, _, err := apiClient.V2API.Auth(ctx).Auth(akeyless.Auth{...}).Execute()
1582    body.push(GoStmt::ShortDecl {
1583        names: vec![
1584            "authOut".to_string(),
1585            "_".to_string(),
1586            "err".to_string(),
1587        ],
1588        values: vec![GoExpr::call(
1589            GoExpr::sel(
1590                GoExpr::call(
1591                    GoExpr::sel(
1592                        GoExpr::call(
1593                            GoExpr::sel(
1594                                GoExpr::sel(GoExpr::ident("apiClient"), "V2API"),
1595                                "Auth",
1596                            ),
1597                            vec![GoExpr::ident("ctx")],
1598                        ),
1599                        "Auth",
1600                    ),
1601                    vec![GoExpr::Composite {
1602                        ty: GoType::qualified("akeyless", "Auth"),
1603                        fields: vec![
1604                            (
1605                                Some("AccessId".to_string()),
1606                                GoExpr::AddressOf(Box::new(GoExpr::ident("accessID"))),
1607                            ),
1608                            (
1609                                Some("AccessKey".to_string()),
1610                                GoExpr::AddressOf(Box::new(GoExpr::ident("accessKey"))),
1611                            ),
1612                            (
1613                                Some("AccessType".to_string()),
1614                                GoExpr::AddressOf(Box::new(GoExpr::ident("accessType"))),
1615                            ),
1616                        ],
1617                        addr_of: false,
1618                    }],
1619                ),
1620                "Execute",
1621            ),
1622            vec![],
1623        )],
1624    });
1625    body.push(GoStmt::If {
1626        init: None,
1627        cond: GoExpr::ident("err != nil"),
1628        body: {
1629            let mut b = GoBlock::new();
1630            b.push(GoStmt::Return(vec![
1631                GoExpr::nil(),
1632                GoExpr::call(
1633                    GoExpr::path(&["fmt", "Errorf"]),
1634                    vec![
1635                        GoExpr::str("akeyless /auth exchange failed: %w"),
1636                        GoExpr::ident("err"),
1637                    ],
1638                ),
1639            ]));
1640            b
1641        },
1642        else_body: None,
1643    });
1644    body.push(GoStmt::If {
1645        init: None,
1646        cond: GoExpr::ident(
1647            "authOut == nil || authOut.Token == nil || *authOut.Token == \"\"",
1648        ),
1649        body: {
1650            let mut b = GoBlock::new();
1651            b.push(GoStmt::Return(vec![
1652                GoExpr::nil(),
1653                GoExpr::call(
1654                    GoExpr::path(&["errors", "New"]),
1655                    vec![GoExpr::str("akeyless /auth returned empty session token")],
1656                ),
1657            ]));
1658            b
1659        },
1660        else_body: None,
1661    });
1662    body.push(GoStmt::Blank);
1663    body.push(GoStmt::Return(vec![
1664        GoExpr::Composite {
1665            ty: GoType::named("external"),
1666            fields: vec![
1667                (Some("client".to_string()), GoExpr::ident("apiClient")),
1668                (
1669                    Some("token".to_string()),
1670                    GoExpr::Star(Box::new(GoExpr::sel(
1671                        GoExpr::ident("authOut"),
1672                        "Token",
1673                    ))),
1674                ),
1675            ],
1676            addr_of: true,
1677        },
1678        GoExpr::nil(),
1679    ]));
1680
1681    GoFuncDecl {
1682        name: "Connect".to_string(),
1683        doc: None,
1684        recv: Some(GoRecv {
1685            name: "c".to_string(),
1686            ty: GoType::pointer(GoType::named("connector")),
1687        }),
1688        params: vec![
1689            GoParam {
1690                name: "ctx".to_string(),
1691                ty: GoType::qualified("context", "Context"),
1692            },
1693            GoParam {
1694                name: "mg".to_string(),
1695                ty: GoType::qualified("resource", "Managed"),
1696            },
1697        ],
1698        returns: vec![
1699            GoType::qualified("managed", "ExternalClient"),
1700            GoType::named("error"),
1701        ],
1702        body,
1703    }
1704}
1705
1706fn creds_unused() {} // silence — `creds` is referenced in the return; the var doesn't go unused
1707
1708fn build_observe_func(resource: &IacResource, kind: &str, shape: &ResourceShape, body_sigs: &SharedBodySigMap) -> GoFuncDecl {
1709    if shape.stub {
1710        return build_stub_observe(kind);
1711    }
1712    let read_method = sdk_naming::go_method_name(&resource.crud.read_schema);
1713    let read_body_type = sdk_naming::go_body_type_name(&resource.crud.read_schema);
1714
1715    // Always "cr", never body_uses_cr-conditional: Observe unconditionally
1716    // calls cr.SetConditions(xpv1.Available()) below, independent of
1717    // whether the request body itself references cr.
1718    let mut body = type_assert_into_cr_named(kind, &observation_return_path(), "cr");
1719    let (preamble, composite) = build_request_body(&read_body_type, shape, CrudMethod::Read, resource, body_sigs);
1720    for s in preamble {
1721        body.push(s);
1722    }
1723    body.push(GoStmt::ShortDecl {
1724        names: vec!["body".to_string()],
1725        values: vec![composite],
1726    });
1727    // _, resp, err := e.client.V2API.<read_method>(ctx).<read_body_type>(body).Execute()
1728    body.push(sdk_call_capture_resp(&read_method, &read_body_type));
1729    // if err != nil {
1730    //   if resp != nil && resp.StatusCode == http.StatusNotFound {
1731    //     return managed.ExternalObservation{ResourceExists: false}, nil
1732    //   }
1733    //   return managed.ExternalObservation{}, err
1734    // }
1735    body.push(GoStmt::If {
1736        init: None,
1737        cond: GoExpr::ident("err != nil"),
1738        body: {
1739            let mut b = GoBlock::new();
1740            b.push(GoStmt::Comment(
1741                "Observed an error. If the upstream API reports 404 the resource".to_string(),
1742            ));
1743            b.push(GoStmt::Comment(
1744                "is absent and the reconciler should advance to Create.".to_string(),
1745            ));
1746            b.push(GoStmt::If {
1747                init: None,
1748                cond: GoExpr::ident("resp != nil && resp.StatusCode == http.StatusNotFound"),
1749                body: {
1750                    let mut nb = GoBlock::new();
1751                    nb.push(GoStmt::Return(vec![
1752                        GoExpr::Composite {
1753                            ty: GoType::qualified("managed", "ExternalObservation"),
1754                            fields: vec![(
1755                                Some("ResourceExists".to_string()),
1756                                GoExpr::Lit(GoLit::Bool(false)),
1757                            )],
1758                            addr_of: false,
1759                        },
1760                        GoExpr::nil(),
1761                    ]));
1762                    nb
1763                },
1764                else_body: None,
1765            });
1766            b.push(GoStmt::Return(vec![
1767                GoExpr::Composite {
1768                    ty: GoType::qualified("managed", "ExternalObservation"),
1769                    fields: vec![],
1770                    addr_of: false,
1771                },
1772                GoExpr::ident("err"),
1773            ]));
1774            b
1775        },
1776        else_body: None,
1777    });
1778    body.push(GoStmt::Blank);
1779    // cr.SetConditions(xpv1.Available())
1780    body.push(GoStmt::Expr(GoExpr::call(
1781        GoExpr::sel(GoExpr::ident("cr"), "SetConditions"),
1782        vec![GoExpr::call(
1783            GoExpr::path(&["xpv1", "Available"]),
1784            vec![],
1785        )],
1786    )));
1787    // return managed.ExternalObservation{ResourceExists: true, ResourceUpToDate: true}, nil
1788    body.push(GoStmt::Comment(
1789        "ResourceUpToDate=true short-circuits the spec↔atProvider diff;".to_string(),
1790    ));
1791    body.push(GoStmt::Comment(
1792        "structural diff lands in controller-iter-2.".to_string(),
1793    ));
1794    body.push(GoStmt::Return(vec![
1795        GoExpr::Composite {
1796            ty: GoType::qualified("managed", "ExternalObservation"),
1797            fields: vec![
1798                (Some("ResourceExists".to_string()), GoExpr::Lit(GoLit::Bool(true))),
1799                (
1800                    Some("ResourceUpToDate".to_string()),
1801                    GoExpr::Lit(GoLit::Bool(true)),
1802                ),
1803            ],
1804            addr_of: false,
1805        },
1806        GoExpr::nil(),
1807    ]));
1808
1809    GoFuncDecl {
1810        name: "Observe".to_string(),
1811        doc: Some(
1812            "Observe queries the upstream provider for the resource's current state.\nThe returned ExternalObservation tells the managed-resource reconciler\n(a) whether the resource exists upstream and (b) whether its observed\nstate matches the declared spec."
1813                .to_string(),
1814        ),
1815        recv: Some(GoRecv {
1816            name: "e".to_string(),
1817            ty: GoType::pointer(GoType::named("external")),
1818        }),
1819        params: vec![
1820            GoParam {
1821                name: "ctx".to_string(),
1822                ty: GoType::qualified("context", "Context"),
1823            },
1824            GoParam {
1825                name: "mg".to_string(),
1826                ty: GoType::qualified("resource", "Managed"),
1827            },
1828        ],
1829        returns: vec![
1830            GoType::qualified("managed", "ExternalObservation"),
1831            GoType::named("error"),
1832        ],
1833        body,
1834    }
1835}
1836
1837fn build_create_func(resource: &IacResource, kind: &str, shape: &ResourceShape, body_sigs: &SharedBodySigMap) -> GoFuncDecl {
1838    if shape.stub {
1839        return build_stub_create(kind);
1840    }
1841    let create_method = sdk_naming::go_method_name(&resource.crud.create_schema);
1842    let create_body_type = sdk_naming::go_body_type_name(&resource.crud.create_schema);
1843
1844    let create_cr_name = if shape.body_uses_cr(CrudMethod::Create) { "cr" } else { "_" };
1845    let mut body = type_assert_into_cr_named(kind, &creation_return_path(), create_cr_name);
1846    let (preamble, composite) = build_request_body(&create_body_type, shape, CrudMethod::Create, resource, body_sigs);
1847    for s in preamble {
1848        body.push(s);
1849    }
1850    body.push(GoStmt::ShortDecl {
1851        names: vec!["body".to_string()],
1852        values: vec![composite],
1853    });
1854    body.push(GoStmt::Comment(
1855        "TODO controller-iter-2: map cr.Spec.ForProvider fields → body fields".to_string(),
1856    ));
1857    body.push(sdk_call_three_underscores(
1858        &create_method,
1859        &create_body_type,
1860    ));
1861    body.push(GoStmt::Return(vec![
1862        GoExpr::Composite {
1863            ty: GoType::qualified("managed", "ExternalCreation"),
1864            fields: vec![],
1865            addr_of: false,
1866        },
1867        GoExpr::ident("err"),
1868    ]));
1869
1870    GoFuncDecl {
1871        name: "Create".to_string(),
1872        doc: Some("Create provisions the resource upstream.".to_string()),
1873        recv: Some(GoRecv {
1874            name: "e".to_string(),
1875            ty: GoType::pointer(GoType::named("external")),
1876        }),
1877        params: vec![
1878            GoParam {
1879                name: "ctx".to_string(),
1880                ty: GoType::qualified("context", "Context"),
1881            },
1882            GoParam {
1883                name: "mg".to_string(),
1884                ty: GoType::qualified("resource", "Managed"),
1885            },
1886        ],
1887        returns: vec![
1888            GoType::qualified("managed", "ExternalCreation"),
1889            GoType::named("error"),
1890        ],
1891        body,
1892    }
1893}
1894
1895fn build_update_func(resource: &IacResource, kind: &str, shape: &ResourceShape, body_sigs: &SharedBodySigMap) -> GoFuncDecl {
1896    if shape.stub {
1897        return build_stub_update(kind);
1898    }
1899    let Some(update_schema) = resource.crud.update_schema.as_deref() else {
1900        // No-op for resources without an update endpoint
1901        let mut body = GoBlock::new();
1902        body.push(GoStmt::ShortDecl {
1903            names: vec!["_".to_string(), "ok".to_string()],
1904            values: vec![GoExpr::TypeAssert {
1905                x: Box::new(GoExpr::ident("mg")),
1906                ty: GoType::pointer(GoType::qualified("v1alpha1", kind)),
1907                with_ok: true,
1908            }],
1909        });
1910        body.push(GoStmt::If {
1911            init: None,
1912            cond: GoExpr::ident("!ok"),
1913            body: {
1914                let mut b = GoBlock::new();
1915                b.push(GoStmt::Return(vec![
1916                    GoExpr::Composite {
1917                        ty: GoType::qualified("managed", "ExternalUpdate"),
1918                        fields: vec![],
1919                        addr_of: false,
1920                    },
1921                    GoExpr::call(
1922                        GoExpr::path(&["errors", "New"]),
1923                        vec![GoExpr::str(&format!("expected *v1alpha1.{kind}"))],
1924                    ),
1925                ]));
1926                b
1927            },
1928            else_body: None,
1929        });
1930        body.push(GoStmt::Return(vec![
1931            GoExpr::Composite {
1932                ty: GoType::qualified("managed", "ExternalUpdate"),
1933                fields: vec![],
1934                addr_of: false,
1935            },
1936            GoExpr::nil(),
1937        ]));
1938        return GoFuncDecl {
1939            name: "Update".to_string(),
1940            doc: Some(
1941                "Update is a no-op — this resource type has no update endpoint.\nSpec changes that mutate immutable fields trigger force-replace via\nthe controller-runtime managed reconciler."
1942                    .to_string(),
1943            ),
1944            recv: Some(GoRecv {
1945                name: "e".to_string(),
1946                ty: GoType::pointer(GoType::named("external")),
1947            }),
1948            params: vec![
1949                GoParam {
1950                    name: "_".to_string(),
1951                    ty: GoType::qualified("context", "Context"),
1952                },
1953                GoParam {
1954                    name: "mg".to_string(),
1955                    ty: GoType::qualified("resource", "Managed"),
1956                },
1957            ],
1958            returns: vec![
1959                GoType::qualified("managed", "ExternalUpdate"),
1960                GoType::named("error"),
1961            ],
1962            body,
1963        };
1964    };
1965
1966    let update_method = sdk_naming::go_method_name(update_schema);
1967    let update_body_type = sdk_naming::go_body_type_name(update_schema);
1968
1969    let update_cr_name = if shape.body_uses_cr(CrudMethod::Update) { "cr" } else { "_" };
1970    let mut body = type_assert_into_cr_named(kind, &update_return_path(), update_cr_name);
1971    let (preamble, composite) = build_request_body(&update_body_type, shape, CrudMethod::Update, resource, body_sigs);
1972    for s in preamble {
1973        body.push(s);
1974    }
1975    body.push(GoStmt::ShortDecl {
1976        names: vec!["body".to_string()],
1977        values: vec![composite],
1978    });
1979    body.push(GoStmt::Comment(
1980        "TODO controller-iter-2: map mutable cr.Spec.ForProvider fields → body fields".to_string(),
1981    ));
1982    body.push(sdk_call_three_underscores(
1983        &update_method,
1984        &update_body_type,
1985    ));
1986    body.push(GoStmt::Return(vec![
1987        GoExpr::Composite {
1988            ty: GoType::qualified("managed", "ExternalUpdate"),
1989            fields: vec![],
1990            addr_of: false,
1991        },
1992        GoExpr::ident("err"),
1993    ]));
1994
1995    GoFuncDecl {
1996        name: "Update".to_string(),
1997        doc: Some(
1998            "Update reconciles the upstream resource against the declared spec.".to_string(),
1999        ),
2000        recv: Some(GoRecv {
2001            name: "e".to_string(),
2002            ty: GoType::pointer(GoType::named("external")),
2003        }),
2004        params: vec![
2005            GoParam {
2006                name: "ctx".to_string(),
2007                ty: GoType::qualified("context", "Context"),
2008            },
2009            GoParam {
2010                name: "mg".to_string(),
2011                ty: GoType::qualified("resource", "Managed"),
2012            },
2013        ],
2014        returns: vec![
2015            GoType::qualified("managed", "ExternalUpdate"),
2016            GoType::named("error"),
2017        ],
2018        body,
2019    }
2020}
2021
2022fn build_delete_func(resource: &IacResource, kind: &str, shape: &ResourceShape, body_sigs: &SharedBodySigMap) -> GoFuncDecl {
2023    if shape.stub {
2024        return build_stub_delete(kind);
2025    }
2026    let delete_method = sdk_naming::go_method_name(&resource.crud.delete_schema);
2027    let delete_body_type = sdk_naming::go_body_type_name(&resource.crud.delete_schema);
2028
2029    // crossplane-runtime v1.18 changed Delete's signature from `error` to
2030    // `(managed.ExternalDelete, error)`. The zero ExternalDelete value is
2031    // returned on success.
2032    let zero_external_delete = GoExpr::Composite {
2033        ty: GoType::qualified("managed", "ExternalDelete"),
2034        fields: vec![],
2035        addr_of: false,
2036    };
2037
2038    // Type assert: `cr, ok :=` when the body uses cr; `_, ok :=` when
2039    // it doesn't (NoIdentifier templates skip cr in the body).
2040    let cr_name = if shape.body_uses_cr(CrudMethod::Delete) { "cr" } else { "_" };
2041    let mut body = GoBlock::new();
2042    body.push(GoStmt::ShortDecl {
2043        names: vec![cr_name.to_string(), "ok".to_string()],
2044        values: vec![GoExpr::TypeAssert {
2045            x: Box::new(GoExpr::ident("mg")),
2046            ty: GoType::pointer(GoType::qualified("v1alpha1", kind)),
2047            with_ok: true,
2048        }],
2049    });
2050    body.push(GoStmt::If {
2051        init: None,
2052        cond: GoExpr::ident("!ok"),
2053        body: {
2054            let mut b = GoBlock::new();
2055            b.push(GoStmt::Return(vec![
2056                zero_external_delete.clone(),
2057                GoExpr::call(
2058                    GoExpr::path(&["errors", "New"]),
2059                    vec![GoExpr::str(&format!("expected *v1alpha1.{kind}"))],
2060                ),
2061            ]));
2062            b
2063        },
2064        else_body: None,
2065    });
2066    body.push(GoStmt::Blank);
2067    let (preamble, composite) = build_request_body(&delete_body_type, shape, CrudMethod::Delete, resource, body_sigs);
2068    for s in preamble {
2069        body.push(s);
2070    }
2071    body.push(GoStmt::ShortDecl {
2072        names: vec!["body".to_string()],
2073        values: vec![composite],
2074    });
2075    body.push(sdk_call_capture_resp(&delete_method, &delete_body_type));
2076    // Delete is idempotent: if the upstream API reports 404 the resource
2077    // is already gone, which is the desired terminal state.
2078    body.push(GoStmt::If {
2079        init: None,
2080        cond: GoExpr::ident(
2081            "err != nil && resp != nil && resp.StatusCode == http.StatusNotFound",
2082        ),
2083        body: {
2084            let mut b = GoBlock::new();
2085            b.push(GoStmt::Return(vec![
2086                zero_external_delete.clone(),
2087                GoExpr::nil(),
2088            ]));
2089            b
2090        },
2091        else_body: None,
2092    });
2093    body.push(GoStmt::Return(vec![
2094        zero_external_delete,
2095        GoExpr::ident("err"),
2096    ]));
2097
2098    GoFuncDecl {
2099        name: "Delete".to_string(),
2100        doc: Some(
2101            "Delete removes the upstream resource. Idempotent on NotFound.\nSignature follows crossplane-runtime v1.18+: returns (ExternalDelete, error)."
2102                .to_string(),
2103        ),
2104        recv: Some(GoRecv {
2105            name: "e".to_string(),
2106            ty: GoType::pointer(GoType::named("external")),
2107        }),
2108        params: vec![
2109            GoParam {
2110                name: "ctx".to_string(),
2111                ty: GoType::qualified("context", "Context"),
2112            },
2113            GoParam {
2114                name: "mg".to_string(),
2115                ty: GoType::qualified("resource", "Managed"),
2116            },
2117        ],
2118        returns: vec![
2119            GoType::qualified("managed", "ExternalDelete"),
2120            GoType::named("error"),
2121        ],
2122        body,
2123    }
2124}
2125
2126// ── Stub controllers (composite-key / mixed-identifier resources) ────────
2127//
2128// Resources whose SDK body shape requires composite keys
2129// (RoleName+Path, RoleName+AmName), mixed-per-CRUD-op identifiers
2130// (Name on Create vs Id on Get/Delete), or singleton bodies with no
2131// identifier field, get a stub controller that satisfies the
2132// ExternalClient interface but no-ops every reconcile call. M3.2
2133// graduates each one as the body-mapping work lands.
2134
2135fn build_stub_observe(kind: &str) -> GoFuncDecl {
2136    let mut body = type_assert_discard_cr(kind, &observation_return_path());
2137    body.push(GoStmt::Comment(
2138        "Stub: body-mapping pending M3.2 graduation — returns ResourceExists=false".to_string(),
2139    ));
2140    body.push(GoStmt::Comment(
2141        "so the reconciler stays idle for resources with composite-key shapes.".to_string(),
2142    ));
2143    body.push(GoStmt::Return(vec![
2144        GoExpr::Composite {
2145            ty: GoType::qualified("managed", "ExternalObservation"),
2146            fields: vec![],
2147            addr_of: false,
2148        },
2149        GoExpr::nil(),
2150    ]));
2151    GoFuncDecl {
2152        name: "Observe".to_string(),
2153        doc: Some(
2154            "Observe — STUB. Body-mapping pending M3.2 graduation for resources whose\nSDK body shape requires composite keys / mixed-per-CRUD identifiers.\nReturns an empty ExternalObservation so the reconciler stays idle."
2155                .to_string(),
2156        ),
2157        recv: Some(GoRecv {
2158            name: "e".to_string(),
2159            ty: GoType::pointer(GoType::named("external")),
2160        }),
2161        params: vec![
2162            GoParam {
2163                name: "ctx".to_string(),
2164                ty: GoType::qualified("context", "Context"),
2165            },
2166            GoParam {
2167                name: "mg".to_string(),
2168                ty: GoType::qualified("resource", "Managed"),
2169            },
2170        ],
2171        returns: vec![
2172            GoType::qualified("managed", "ExternalObservation"),
2173            GoType::named("error"),
2174        ],
2175        body,
2176    }
2177}
2178
2179fn build_stub_create(kind: &str) -> GoFuncDecl {
2180    let mut body = type_assert_discard_cr(kind, &creation_return_path());
2181    body.push(GoStmt::Comment(
2182        "Stub: body-mapping pending M3.2 graduation.".to_string(),
2183    ));
2184    body.push(GoStmt::Return(vec![
2185        GoExpr::Composite {
2186            ty: GoType::qualified("managed", "ExternalCreation"),
2187            fields: vec![],
2188            addr_of: false,
2189        },
2190        GoExpr::nil(),
2191    ]));
2192    GoFuncDecl {
2193        name: "Create".to_string(),
2194        doc: Some("Create — STUB. Body-mapping pending M3.2 graduation.".to_string()),
2195        recv: Some(GoRecv {
2196            name: "e".to_string(),
2197            ty: GoType::pointer(GoType::named("external")),
2198        }),
2199        params: vec![
2200            GoParam {
2201                name: "ctx".to_string(),
2202                ty: GoType::qualified("context", "Context"),
2203            },
2204            GoParam {
2205                name: "mg".to_string(),
2206                ty: GoType::qualified("resource", "Managed"),
2207            },
2208        ],
2209        returns: vec![
2210            GoType::qualified("managed", "ExternalCreation"),
2211            GoType::named("error"),
2212        ],
2213        body,
2214    }
2215}
2216
2217fn build_stub_update(kind: &str) -> GoFuncDecl {
2218    let mut body = type_assert_discard_cr(kind, &update_return_path());
2219    body.push(GoStmt::Comment(
2220        "Stub: body-mapping pending M3.2 graduation.".to_string(),
2221    ));
2222    body.push(GoStmt::Return(vec![
2223        GoExpr::Composite {
2224            ty: GoType::qualified("managed", "ExternalUpdate"),
2225            fields: vec![],
2226            addr_of: false,
2227        },
2228        GoExpr::nil(),
2229    ]));
2230    GoFuncDecl {
2231        name: "Update".to_string(),
2232        doc: Some("Update — STUB. Body-mapping pending M3.2 graduation.".to_string()),
2233        recv: Some(GoRecv {
2234            name: "e".to_string(),
2235            ty: GoType::pointer(GoType::named("external")),
2236        }),
2237        params: vec![
2238            GoParam {
2239                name: "ctx".to_string(),
2240                ty: GoType::qualified("context", "Context"),
2241            },
2242            GoParam {
2243                name: "mg".to_string(),
2244                ty: GoType::qualified("resource", "Managed"),
2245            },
2246        ],
2247        returns: vec![
2248            GoType::qualified("managed", "ExternalUpdate"),
2249            GoType::named("error"),
2250        ],
2251        body,
2252    }
2253}
2254
2255fn build_stub_delete(kind: &str) -> GoFuncDecl {
2256    // Mirror the type-assert + If !ok prelude from build_delete_func so
2257    // the stub's signature matches non-stub Delete (returns
2258    // managed.ExternalDelete + error per v1.18).
2259    let mut body = GoBlock::new();
2260    body.push(GoStmt::ShortDecl {
2261        names: vec!["_".to_string(), "ok".to_string()],
2262        values: vec![GoExpr::TypeAssert {
2263            x: Box::new(GoExpr::ident("mg")),
2264            ty: GoType::pointer(GoType::qualified("v1alpha1", kind)),
2265            with_ok: true,
2266        }],
2267    });
2268    body.push(GoStmt::If {
2269        init: None,
2270        cond: GoExpr::ident("!ok"),
2271        body: {
2272            let mut b = GoBlock::new();
2273            b.push(GoStmt::Return(vec![
2274                GoExpr::Composite {
2275                    ty: GoType::qualified("managed", "ExternalDelete"),
2276                    fields: vec![],
2277                    addr_of: false,
2278                },
2279                GoExpr::call(
2280                    GoExpr::path(&["errors", "New"]),
2281                    vec![GoExpr::str(&format!("expected *v1alpha1.{kind}"))],
2282                ),
2283            ]));
2284            b
2285        },
2286        else_body: None,
2287    });
2288    body.push(GoStmt::Comment(
2289        "Stub: body-mapping pending M3.2 graduation.".to_string(),
2290    ));
2291    body.push(GoStmt::Return(vec![
2292        GoExpr::Composite {
2293            ty: GoType::qualified("managed", "ExternalDelete"),
2294            fields: vec![],
2295            addr_of: false,
2296        },
2297        GoExpr::nil(),
2298    ]));
2299    GoFuncDecl {
2300        name: "Delete".to_string(),
2301        doc: Some("Delete — STUB. Body-mapping pending M3.2 graduation.".to_string()),
2302        recv: Some(GoRecv {
2303            name: "e".to_string(),
2304            ty: GoType::pointer(GoType::named("external")),
2305        }),
2306        params: vec![
2307            GoParam {
2308                name: "ctx".to_string(),
2309                ty: GoType::qualified("context", "Context"),
2310            },
2311            GoParam {
2312                name: "mg".to_string(),
2313                ty: GoType::qualified("resource", "Managed"),
2314            },
2315        ],
2316        returns: vec![
2317            GoType::qualified("managed", "ExternalDelete"),
2318            GoType::named("error"),
2319        ],
2320        body,
2321    }
2322}
2323
2324// ── Per-method body helpers ──────────────────────────────────────────────
2325
2326/// Like [`type_assert_into_cr`] but discards the receiver pointer
2327/// (`_, ok :=` instead of `cr, ok :=`). Used by stub controllers
2328/// that only need to verify the type matches.
2329fn type_assert_discard_cr(kind: &str, return_zero: &GoType) -> GoBlock {
2330    let mut b = GoBlock::new();
2331    b.push(GoStmt::ShortDecl {
2332        names: vec!["_".to_string(), "ok".to_string()],
2333        values: vec![GoExpr::TypeAssert {
2334            x: Box::new(GoExpr::ident("mg")),
2335            ty: GoType::pointer(GoType::qualified("v1alpha1", kind)),
2336            with_ok: true,
2337        }],
2338    });
2339    b.push(GoStmt::If {
2340        init: None,
2341        cond: GoExpr::ident("!ok"),
2342        body: {
2343            let mut inner = GoBlock::new();
2344            inner.push(GoStmt::Return(vec![
2345                GoExpr::Composite {
2346                    ty: return_zero.clone(),
2347                    fields: vec![],
2348                    addr_of: false,
2349                },
2350                GoExpr::call(
2351                    GoExpr::path(&["errors", "New"]),
2352                    vec![GoExpr::str(&format!("expected *v1alpha1.{kind}"))],
2353                ),
2354            ]));
2355            inner
2356        },
2357        else_body: None,
2358    });
2359    b.push(GoStmt::Blank);
2360    b
2361}
2362
2363/// `cr, ok := mg.(*v1alpha1.<Kind>)` (or `_, ok := ...` when the
2364/// caller's method body never reads `cr` — a `BodyTemplate::NoIdentifier`
2365/// shape, see [`ResourceShape::body_uses_cr`] — pass `"_"` so the
2366/// emitted Go doesn't trip the compiler's declared-and-not-used check,
2367/// mirroring `build_delete_func`'s pre-existing `cr_name` pattern).
2368fn type_assert_into_cr_named(kind: &str, return_zero: &GoType, cr_name: &str) -> GoBlock {
2369    // cr, ok := mg.(*v1alpha1.<Kind>)   (or `_, ok := ...` when unused)
2370    // if !ok { return <ZeroOf>{}, errors.New("expected *v1alpha1.<Kind>") }
2371    let mut b = GoBlock::new();
2372    b.push(GoStmt::ShortDecl {
2373        names: vec![cr_name.to_string(), "ok".to_string()],
2374        values: vec![GoExpr::TypeAssert {
2375            x: Box::new(GoExpr::ident("mg")),
2376            ty: GoType::pointer(GoType::qualified("v1alpha1", kind)),
2377            with_ok: true,
2378        }],
2379    });
2380    b.push(GoStmt::If {
2381        init: None,
2382        cond: GoExpr::ident("!ok"),
2383        body: {
2384            let mut inner = GoBlock::new();
2385            inner.push(GoStmt::Return(vec![
2386                GoExpr::Composite {
2387                    ty: return_zero.clone(),
2388                    fields: vec![],
2389                    addr_of: false,
2390                },
2391                GoExpr::call(
2392                    GoExpr::path(&["errors", "New"]),
2393                    vec![GoExpr::str(&format!("expected *v1alpha1.{kind}"))],
2394                ),
2395            ]));
2396            inner
2397        },
2398        else_body: None,
2399    });
2400    b.push(GoStmt::Blank);
2401    let _ = cr_ident_unused();
2402    b
2403}
2404
2405fn cr_ident_unused() {}
2406
2407fn observation_return_path() -> GoType {
2408    GoType::qualified("managed", "ExternalObservation")
2409}
2410fn creation_return_path() -> GoType {
2411    GoType::qualified("managed", "ExternalCreation")
2412}
2413fn update_return_path() -> GoType {
2414    GoType::qualified("managed", "ExternalUpdate")
2415}
2416
2417fn sdk_call_chain(method: &str, body_type: &str) -> GoExpr {
2418    // e.client.V2API.<method>(ctx).<body_type>(body).Execute()
2419    GoExpr::call(
2420        GoExpr::sel(
2421            GoExpr::call(
2422                GoExpr::sel(
2423                    GoExpr::call(
2424                        GoExpr::sel(
2425                            GoExpr::sel(
2426                                GoExpr::sel(GoExpr::ident("e"), "client"),
2427                                "V2API",
2428                            ),
2429                            method,
2430                        ),
2431                        vec![GoExpr::ident("ctx")],
2432                    ),
2433                    body_type,
2434                ),
2435                vec![GoExpr::ident("body")],
2436            ),
2437            "Execute",
2438        ),
2439        vec![],
2440    )
2441}
2442
2443fn sdk_call_three_underscores(method: &str, body_type: &str) -> GoStmt {
2444    // _, _, err := e.client.V2API.<method>(ctx).<body_type>(body).Execute()
2445    GoStmt::ShortDecl {
2446        names: vec!["_".to_string(), "_".to_string(), "err".to_string()],
2447        values: vec![sdk_call_chain(method, body_type)],
2448    }
2449}
2450
2451fn sdk_call_capture_resp(method: &str, body_type: &str) -> GoStmt {
2452    // _, resp, err := e.client.V2API.<method>(ctx).<body_type>(body).Execute()
2453    GoStmt::ShortDecl {
2454        names: vec!["_".to_string(), "resp".to_string(), "err".to_string()],
2455        values: vec![sdk_call_chain(method, body_type)],
2456    }
2457}
2458
2459// ── Naming helpers (re-exported public surface kept stable) ──────────────
2460
2461/// The Go package name for this resource's controller — `to_snake_case`'d
2462/// type name (e.g. `authmethodapikey`).
2463#[must_use]
2464pub fn package_name(resource: &IacResource, provider: &IacProvider) -> String {
2465    strip_provider_prefix(&resource.name, &provider.name)
2466        .replace('_', "")
2467        .to_lowercase()
2468}
2469
2470/// The Go-exported CRD kind (e.g. `AuthMethodApiKey`).
2471#[must_use]
2472pub fn cr_kind(resource: &IacResource, provider: &IacProvider) -> String {
2473    to_pascal_case(strip_provider_prefix(&resource.name, &provider.name))
2474}
2475
2476#[cfg(test)]
2477mod tests {
2478    use super::*;
2479    use iac_forge::ir::{AuthInfo, CrudInfo, IdentityInfo};
2480    use std::collections::BTreeMap;
2481
2482    fn akeyless_provider() -> IacProvider {
2483        IacProvider {
2484            name: "akeyless".to_string(),
2485            description: "Akeyless Vault Provider".to_string(),
2486            version: "1.0.0".to_string(),
2487            auth: AuthInfo::default(),
2488            skip_fields: vec![],
2489            platform_config: BTreeMap::new(),
2490        }
2491    }
2492
2493    fn auth_method_api_key() -> IacResource {
2494        IacResource {
2495            name: "akeyless_auth_method_api_key".to_string(),
2496            description: "Manages an API key authentication method".to_string(),
2497            category: "auth_method".to_string(),
2498            crud: CrudInfo {
2499                create_endpoint: "/auth-method-create-api-key".to_string(),
2500                create_schema: "authMethodCreateApiKey".to_string(),
2501                update_endpoint: Some("/auth-method-update-api-key".to_string()),
2502                update_schema: Some("authMethodUpdateApiKey".to_string()),
2503                read_endpoint: "/get-auth-method".to_string(),
2504                read_schema: "getAuthMethod".to_string(),
2505                read_response_schema: Some("AuthMethod".to_string()),
2506                delete_endpoint: "/delete-auth-method".to_string(),
2507                delete_schema: "deleteAuthMethod".to_string(),
2508            },
2509            attributes: vec![],
2510            identity: IdentityInfo {
2511                id_field: "name".to_string(),
2512                import_field: "name".to_string(),
2513                force_replace_fields: vec!["name".to_string()],
2514            },
2515            read_mapping: Default::default(),
2516        }
2517    }
2518
2519    fn role_no_update() -> IacResource {
2520        IacResource {
2521            name: "akeyless_role".to_string(),
2522            description: "Manages a role".to_string(),
2523            category: "role".to_string(),
2524            crud: CrudInfo {
2525                create_endpoint: "/create-role".to_string(),
2526                create_schema: "createRole".to_string(),
2527                update_endpoint: None,
2528                update_schema: None,
2529                read_endpoint: "/get-role".to_string(),
2530                read_schema: "getRole".to_string(),
2531                read_response_schema: None,
2532                delete_endpoint: "/delete-role".to_string(),
2533                delete_schema: "deleteRole".to_string(),
2534            },
2535            attributes: vec![],
2536            identity: IdentityInfo {
2537                id_field: "name".to_string(),
2538                import_field: "name".to_string(),
2539                force_replace_fields: vec!["name".to_string()],
2540            },
2541            read_mapping: Default::default(),
2542        }
2543    }
2544
2545    // ── AST-shape tests ──────────────────────────────────────────────────
2546
2547    #[test]
2548    fn controller_file_has_expected_decl_sequence() {
2549        let f = build_controller_file(
2550            &auth_method_api_key(),
2551            &akeyless_provider(),
2552            &ControllerConfig::akeyless_default(),
2553        );
2554        let decl_names: Vec<String> = f
2555            .decls
2556            .iter()
2557            .filter_map(|d| match d {
2558                GoDecl::Type(t) => Some(t.name.clone()),
2559                GoDecl::Func(fd) => Some(fd.name.clone()),
2560                _ => None,
2561            })
2562            .collect();
2563        assert_eq!(
2564            decl_names,
2565            vec![
2566                "akeylessCredentials".to_string(),
2567                "external".to_string(),
2568                "Setup".to_string(),
2569                "connector".to_string(),
2570                "Connect".to_string(),
2571                "Observe".to_string(),
2572                "Create".to_string(),
2573                "Update".to_string(),
2574                "Delete".to_string(),
2575                "Disconnect".to_string(),
2576            ]
2577        );
2578    }
2579
2580    #[test]
2581    fn external_struct_has_client_and_token_fields() {
2582        let t = build_external_struct_type();
2583        let GoTypeBody::Struct(fields) = &t.body else {
2584            panic!()
2585        };
2586        let names: Vec<&str> = fields.iter().filter_map(|f| f.name.as_deref()).collect();
2587        assert_eq!(names, vec!["client", "token"]);
2588        // client is *akeyless.APIClient
2589        assert!(matches!(
2590            fields[0].ty,
2591            GoType::Pointer(ref inner) if matches!(
2592                **inner,
2593                GoType::Qualified { ref pkg, ref name } if pkg == "akeyless" && name == "APIClient",
2594            )
2595        ));
2596    }
2597
2598    #[test]
2599    fn setup_returns_complete_chain() {
2600        let f = build_setup_func("Foo");
2601        // Last statement is a Return wrapping a Call to .Complete(r)
2602        let last = f.body.stmts.last().unwrap();
2603        let GoStmt::Return(exprs) = last else {
2604            panic!("expected return")
2605        };
2606        let GoExpr::Call { fun, args } = &exprs[0] else {
2607            panic!("expected call")
2608        };
2609        let GoExpr::Selector { sel, .. } = fun.as_ref() else {
2610            panic!("expected selector")
2611        };
2612        assert_eq!(sel, "Complete");
2613        assert!(matches!(args[0], GoExpr::Ident(ref s) if s == "r"));
2614    }
2615
2616    #[test]
2617    fn observe_calls_correct_sdk_method() {
2618        let f = build_observe_func(&auth_method_api_key(), "AuthMethodApiKey", &ResourceShape::default(), &None);
2619        let rendered = print_file(&{
2620            let mut file = GoFile::new("p");
2621            file.decls.push(GoDecl::Func(f));
2622            file
2623        });
2624        // The rendered chain must call V2API.GetAuthMethod(ctx).GetAuthMethod(body).Execute()
2625        // We assert via substring on the structurally-rendered output —
2626        // failure modes here are SDK-naming bugs, not formatting bugs.
2627        assert!(rendered.contains("e.client.V2API.GetAuthMethod(ctx).GetAuthMethod(body).Execute()"));
2628    }
2629
2630    #[test]
2631    fn create_calls_correct_sdk_method() {
2632        let f = build_create_func(&auth_method_api_key(), "AuthMethodApiKey", &ResourceShape::default(), &None);
2633        let mut file = GoFile::new("p");
2634        file.decls.push(GoDecl::Func(f));
2635        let rendered = print_file(&file);
2636        assert!(rendered.contains(
2637            "e.client.V2API.AuthMethodCreateApiKey(ctx).AuthMethodCreateApiKey(body).Execute()"
2638        ));
2639    }
2640
2641    #[test]
2642    fn update_no_op_branch_for_resources_without_update_schema() {
2643        let f = build_update_func(&role_no_update(), "Role", &ResourceShape::default(), &None);
2644        // Rendering: should NOT contain V2API call
2645        let mut file = GoFile::new("p");
2646        file.decls.push(GoDecl::Func(f));
2647        let rendered = print_file(&file);
2648        assert!(!rendered.contains("V2API."));
2649        assert!(rendered.contains("// Update is a no-op"));
2650    }
2651
2652    #[test]
2653    fn delete_calls_correct_sdk_method() {
2654        let f = build_delete_func(&auth_method_api_key(), "AuthMethodApiKey", &ResourceShape::default(), &None);
2655        let mut file = GoFile::new("p");
2656        file.decls.push(GoDecl::Func(f));
2657        let rendered = print_file(&file);
2658        assert!(rendered.contains(
2659            "e.client.V2API.DeleteAuthMethod(ctx).DeleteAuthMethod(body).Execute()"
2660        ));
2661        // v1.18 return shape — both error paths return managed.ExternalDelete{}
2662        assert!(rendered.contains("return managed.ExternalDelete{}, err"));
2663        assert!(rendered.contains("return managed.ExternalDelete{}, errors.New("));
2664    }
2665
2666    #[test]
2667    fn controller_emits_disconnect_method_for_v1_18() {
2668        // crossplane-runtime v1.18 added Disconnect(ctx) error to
2669        // ExternalClient. *external must implement it; we emit a no-op.
2670        let s = render_controller(
2671            &auth_method_api_key(),
2672            &akeyless_provider(),
2673            &ControllerConfig::akeyless_default(),
2674        );
2675        assert!(s.contains("func (_ *external) Disconnect(_ context.Context) error {"));
2676        assert!(s.contains("holds no long-lived resources"));
2677        // No-op: just `return nil`
2678        assert!(s.contains("return nil"));
2679    }
2680
2681    #[test]
2682    fn setup_func_wraps_logger_in_logging_logr_wrapper() {
2683        // M5.3 regression: managed.WithLogger requires Crossplane's
2684        // logging.Logger interface, not raw logr.Logger from
2685        // controller-runtime. Wrap via logging.NewLogrLogger.
2686        let s = render_controller(
2687            &auth_method_api_key(),
2688            &akeyless_provider(),
2689            &ControllerConfig::akeyless_default(),
2690        );
2691        assert!(s.contains("managed.WithLogger(logging.NewLogrLogger(ctrl.Log.WithName(name)))"));
2692        assert!(s.contains("\"github.com/crossplane/crossplane-runtime/pkg/logging\""));
2693    }
2694
2695    #[test]
2696    fn package_and_kind_naming() {
2697        assert_eq!(
2698            package_name(&auth_method_api_key(), &akeyless_provider()),
2699            "authmethodapikey"
2700        );
2701        assert_eq!(
2702            cr_kind(&auth_method_api_key(), &akeyless_provider()),
2703            "AuthMethodApiKey"
2704        );
2705    }
2706
2707    #[test]
2708    fn rendered_controller_carries_no_format_string_leakage() {
2709        let s = render_controller(
2710            &auth_method_api_key(),
2711            &akeyless_provider(),
2712            &ControllerConfig::akeyless_default(),
2713        );
2714        // No leaked placeholder syntax
2715        assert!(!s.contains("{kind}"));
2716        assert!(!s.contains("{api_group}"));
2717        assert!(!s.contains("{this_pkg}"));
2718        // Code-gen marker
2719        assert!(s.contains("// Code generated by iac-forge. DO NOT EDIT."));
2720    }
2721
2722    #[test]
2723    fn deterministic_render() {
2724        let cfg = ControllerConfig::akeyless_default();
2725        let a = render_controller(&auth_method_api_key(), &akeyless_provider(), &cfg);
2726        let b = render_controller(&auth_method_api_key(), &akeyless_provider(), &cfg);
2727        assert_eq!(a, b);
2728    }
2729
2730    // ── Deeper AST-shape tests (one per emitted function body) ──────────
2731
2732    #[test]
2733    fn observe_body_shape() {
2734        let f = build_observe_func(&auth_method_api_key(), "AuthMethodApiKey", &ResourceShape::default(), &None);
2735        // First two stmts: type-assert short decl, then the !ok if branch.
2736        assert!(matches!(
2737            f.body.stmts[0],
2738            GoStmt::ShortDecl { ref names, .. } if names == &["cr".to_string(), "ok".to_string()]
2739        ));
2740        assert!(matches!(f.body.stmts[1], GoStmt::If { .. }));
2741        // Should declare a `body` short-decl with the read-body composite.
2742        let body_decl = f.body.stmts.iter().find(|s| matches!(
2743            s, GoStmt::ShortDecl { names, .. } if names == &["body".to_string()],
2744        ));
2745        assert!(body_decl.is_some());
2746        // Should `_, resp, err :=` short-decl the SDK chain (resp captured for 404 mapping).
2747        let sdk_call = f.body.stmts.iter().find(|s| matches!(
2748            s, GoStmt::ShortDecl { names, .. }
2749                if names == &["_".to_string(), "resp".to_string(), "err".to_string()],
2750        ));
2751        assert!(sdk_call.is_some());
2752        // The `if err != nil` block must contain a nested `if resp != nil && resp.StatusCode == http.StatusNotFound`
2753        // returning ExternalObservation{ResourceExists: false}, nil.
2754        let err_block = f.body.stmts.iter().find_map(|s| match s {
2755            GoStmt::If { cond, body, .. }
2756                if matches!(cond, GoExpr::Ident(s) if s == "err != nil") =>
2757            {
2758                Some(body)
2759            }
2760            _ => None,
2761        }).expect("err != nil branch present");
2762        let nested_if = err_block.stmts.iter().find_map(|s| match s {
2763            GoStmt::If { cond, body, .. }
2764                if matches!(cond, GoExpr::Ident(s) if s.contains("StatusNotFound")) =>
2765            {
2766                Some(body)
2767            }
2768            _ => None,
2769        }).expect("nested 404 branch present");
2770        let GoStmt::Return(rs) = nested_if.stmts.last().unwrap() else { panic!("expected return"); };
2771        assert!(matches!(rs[1], GoExpr::Lit(GoLit::Nil)));
2772        if let GoExpr::Composite { fields, .. } = &rs[0] {
2773            assert!(fields.iter().any(|(name, val)| {
2774                name.as_deref() == Some("ResourceExists") && matches!(val, GoExpr::Lit(GoLit::Bool(false)))
2775            }), "404 branch must set ResourceExists: false");
2776        } else {
2777            panic!("expected composite return");
2778        }
2779        // Last stmt is a Return with managed.ExternalObservation
2780        let GoStmt::Return(returns) = f.body.stmts.last().unwrap() else {
2781            panic!("expected return")
2782        };
2783        assert_eq!(returns.len(), 2);
2784        assert!(matches!(
2785            returns[0],
2786            GoExpr::Composite {
2787                ty: GoType::Qualified { ref pkg, ref name },
2788                ..
2789            } if pkg == "managed" && name == "ExternalObservation"
2790        ));
2791        assert!(matches!(returns[1], GoExpr::Lit(GoLit::Nil)));
2792    }
2793
2794    #[test]
2795    fn observe_signature_correct() {
2796        let f = build_observe_func(&auth_method_api_key(), "AuthMethodApiKey", &ResourceShape::default(), &None);
2797        assert_eq!(f.name, "Observe");
2798        let recv = f.recv.as_ref().unwrap();
2799        assert_eq!(recv.name, "e");
2800        assert!(matches!(
2801            recv.ty,
2802            GoType::Pointer(ref inner)
2803                if matches!(**inner, GoType::Named(ref n) if n == "external"),
2804        ));
2805        let param_names: Vec<&str> = f.params.iter().map(|p| p.name.as_str()).collect();
2806        assert_eq!(param_names, vec!["ctx", "mg"]);
2807        assert_eq!(f.returns.len(), 2);
2808        assert!(matches!(
2809            f.returns[0],
2810            GoType::Qualified { ref pkg, ref name }
2811                if pkg == "managed" && name == "ExternalObservation",
2812        ));
2813        assert!(matches!(f.returns[1], GoType::Named(ref n) if n == "error"));
2814    }
2815
2816    #[test]
2817    fn create_signature_returns_external_creation() {
2818        let f = build_create_func(&auth_method_api_key(), "AuthMethodApiKey", &ResourceShape::default(), &None);
2819        assert_eq!(f.name, "Create");
2820        assert!(matches!(
2821            f.returns[0],
2822            GoType::Qualified { ref pkg, ref name }
2823                if pkg == "managed" && name == "ExternalCreation",
2824        ));
2825    }
2826
2827    #[test]
2828    fn delete_returns_external_delete_and_error_v1_18() {
2829        let f = build_delete_func(&auth_method_api_key(), "AuthMethodApiKey", &ResourceShape::default(), &None);
2830        assert_eq!(f.returns.len(), 2);
2831        assert!(matches!(
2832            f.returns[0],
2833            GoType::Qualified { ref pkg, ref name }
2834                if pkg == "managed" && name == "ExternalDelete",
2835        ));
2836        assert!(matches!(f.returns[1], GoType::Named(ref n) if n == "error"));
2837    }
2838
2839    #[test]
2840    fn setup_signature_takes_manager_and_poll_interval() {
2841        let f = build_setup_func("Foo");
2842        assert!(f.recv.is_none(), "Setup is a free function, not a method");
2843        let params: Vec<&str> = f.params.iter().map(|p| p.name.as_str()).collect();
2844        assert_eq!(params, vec!["mgr", "pollInterval"]);
2845        assert!(matches!(
2846            f.params[0].ty,
2847            GoType::Qualified { ref pkg, ref name } if pkg == "ctrl" && name == "Manager",
2848        ));
2849        assert!(matches!(
2850            f.params[1].ty,
2851            GoType::Qualified { ref pkg, ref name } if pkg == "time" && name == "Duration",
2852        ));
2853        assert_eq!(f.returns.len(), 1);
2854        assert!(matches!(f.returns[0], GoType::Named(ref n) if n == "error"));
2855    }
2856
2857    #[test]
2858    fn connect_signature_returns_external_client_and_error() {
2859        let f = build_connect_func("Foo");
2860        assert_eq!(f.name, "Connect");
2861        let recv = f.recv.as_ref().unwrap();
2862        assert_eq!(recv.name, "c");
2863        assert!(matches!(
2864            recv.ty,
2865            GoType::Pointer(ref inner)
2866                if matches!(**inner, GoType::Named(ref n) if n == "connector"),
2867        ));
2868        assert!(matches!(
2869            f.returns[0],
2870            GoType::Qualified { ref pkg, ref name }
2871                if pkg == "managed" && name == "ExternalClient",
2872        ));
2873    }
2874
2875    #[test]
2876    fn connect_func_calls_v2api_auth_with_credentials() {
2877        // Render the full controller file and look for the structural shape of
2878        // the /auth round-trip: short-decl naming `authOut, _, err` whose RHS
2879        // selects `Execute` from a chain that hits both `Auth(ctx)` and
2880        // `Auth(akeyless.Auth{...})`. We do not match on raw text — only the
2881        // typed AST shape.
2882        let f = build_controller_file(
2883            &auth_method_api_key(),
2884            &akeyless_provider(),
2885            &ControllerConfig::akeyless_default(),
2886        );
2887        let connect = f.decls.iter().find_map(|d| match d {
2888            GoDecl::Func(fd) if fd.name == "Connect" => Some(fd),
2889            _ => None,
2890        }).expect("Connect declared");
2891        let auth_call = connect.body.stmts.iter().find_map(|s| match s {
2892            GoStmt::ShortDecl { names, values } if names == &[
2893                "authOut".to_string(),
2894                "_".to_string(),
2895                "err".to_string(),
2896            ] => Some(values),
2897            _ => None,
2898        }).expect("authOut, _, err := … short-decl present");
2899        // Verify it is a Call whose head selects "Execute"; we don't traverse
2900        // the entire chain — the printer is round-trip-tested elsewhere.
2901        let GoExpr::Call { fun, .. } = &auth_call[0] else {
2902            panic!("expected a call expr");
2903        };
2904        let GoExpr::Selector { sel, .. } = fun.as_ref() else {
2905            panic!("expected selector at the head");
2906        };
2907        assert_eq!(sel, "Execute", "auth chain must terminate at .Execute()");
2908    }
2909
2910    #[test]
2911    fn credentials_struct_type_emitted_with_four_json_tagged_fields() {
2912        let f = build_controller_file(
2913            &auth_method_api_key(),
2914            &akeyless_provider(),
2915            &ControllerConfig::akeyless_default(),
2916        );
2917        let cred = f.decls.iter().find_map(|d| match d {
2918            GoDecl::Type(td) if td.name == "akeylessCredentials" => Some(td),
2919            _ => None,
2920        }).expect("akeylessCredentials type emitted");
2921        let GoTypeBody::Struct(fields) = &cred.body else {
2922            panic!("akeylessCredentials must be a struct")
2923        };
2924        assert_eq!(fields.len(), 4);
2925        let names: Vec<&str> = fields.iter().filter_map(|f| f.name.as_deref()).collect();
2926        assert_eq!(names, vec!["AccessID", "AccessKey", "AccessIDDash", "AccessKeyDash"]);
2927    }
2928
2929    #[test]
2930    fn create_body_pushes_for_provider_scalar_fields() {
2931        // Build a resource with several scalar attributes; the Create body
2932        // composite must include each as `Pascal: cr.Spec.ForProvider.Pascal`.
2933        use iac_forge::ir::{IacAttribute, IacType};
2934        let mut r = auth_method_api_key();
2935        r.attributes = vec![
2936            IacAttribute {
2937                canonical_name: "name".to_string(),
2938                description: "Name of the auth method".to_string(),
2939                iac_type: IacType::String,
2940                required: true,
2941                computed: false,
2942                sensitive: false,
2943                immutable: true,
2944                api_name: String::new(),
2945                optional: false,
2946                json_encoded: false,
2947                default_value: None,
2948                enum_values: None,
2949                read_path: None,
2950                update_only: false,
2951                ..Default::default()
2952            },
2953            IacAttribute {
2954                canonical_name: "access_expires".to_string(),
2955                description: "Auth method access expiration in seconds".to_string(),
2956                iac_type: IacType::Integer,
2957                required: false,
2958                computed: false,
2959                sensitive: false,
2960                immutable: false,
2961                api_name: String::new(),
2962                optional: false,
2963                json_encoded: false,
2964                default_value: None,
2965                enum_values: None,
2966                read_path: None,
2967                update_only: false,
2968                ..Default::default()
2969            },
2970            IacAttribute {
2971                canonical_name: "force_sub_claims".to_string(),
2972                description: "if true sub-claims are required".to_string(),
2973                iac_type: IacType::Boolean,
2974                required: false,
2975                computed: false,
2976                sensitive: false,
2977                immutable: false,
2978                api_name: String::new(),
2979                optional: false,
2980                json_encoded: false,
2981                default_value: None,
2982                enum_values: None,
2983                read_path: None,
2984                update_only: false,
2985                ..Default::default()
2986            },
2987            IacAttribute {
2988                canonical_name: "computed_id".to_string(),
2989                description: "Read-only".to_string(),
2990                iac_type: IacType::String,
2991                required: false,
2992                computed: true, // must be EXCLUDED
2993                sensitive: false,
2994                immutable: false,
2995                api_name: String::new(),
2996                optional: false,
2997                json_encoded: false,
2998                default_value: None,
2999                enum_values: None,
3000                read_path: None,
3001                update_only: false,
3002                ..Default::default()
3003            },
3004            IacAttribute {
3005                canonical_name: "tags".to_string(),
3006                description: "tags slice".to_string(),
3007                iac_type: IacType::List(Box::new(IacType::String)),
3008                required: false,
3009                computed: false,
3010                sensitive: false,
3011                immutable: false,
3012                api_name: String::new(),
3013                optional: false,
3014                json_encoded: false,
3015                default_value: None,
3016                enum_values: None,
3017                read_path: None,
3018                update_only: false,
3019                ..Default::default()
3020            },
3021        ];
3022        // Test M6.2 broad walk via the manual opt-in path (push_for_provider_fields=true)
3023        // — the M6.4 schema-driven path is exercised in body_signatures::tests.
3024        let mut shape = ResourceShape::default();
3025        shape.push_for_provider_fields = true;
3026        let f = build_create_func(&r, "AuthMethodApiKey", &shape, &None);
3027        // Find the body short-decl
3028        let body_decl = f.body.stmts.iter().find_map(|s| match s {
3029            GoStmt::ShortDecl { names, values } if names == &["body".to_string()] => Some(values),
3030            _ => None,
3031        }).expect("body short-decl present");
3032        let GoExpr::Composite { fields, .. } = &body_decl[0] else {
3033            panic!("expected composite literal for body");
3034        };
3035        let field_names: Vec<&str> = fields
3036            .iter()
3037            .filter_map(|(n, _)| n.as_deref())
3038            .collect();
3039        // Identifier + Token always present
3040        assert!(field_names.contains(&"Name"));
3041        assert!(field_names.contains(&"Token"));
3042        // M6.2: scalar non-computed non-identifier fields pushed
3043        assert!(field_names.contains(&"AccessExpires"), "expected AccessExpires field, got {field_names:?}");
3044        assert!(field_names.contains(&"ForceSubClaims"), "expected ForceSubClaims field, got {field_names:?}");
3045        // Excluded: computed attributes
3046        assert!(!field_names.contains(&"ComputedId"), "computed attr leaked into body, got {field_names:?}");
3047        // Excluded: list/map/object types (slice 1 still opaque-string in types_gen)
3048        assert!(!field_names.contains(&"Tags"), "list attr leaked into body, got {field_names:?}");
3049    }
3050
3051    #[test]
3052    fn read_body_does_not_push_for_provider_fields() {
3053        // Read bodies on akeyless are identifier-only; M6.2 must NOT push
3054        // spec fields into them.
3055        use iac_forge::ir::{IacAttribute, IacType};
3056        let mut r = auth_method_api_key();
3057        r.attributes = vec![
3058            IacAttribute {
3059                canonical_name: "name".to_string(),
3060                description: "".to_string(),
3061                iac_type: IacType::String,
3062                required: true,
3063                computed: false,
3064                sensitive: false,
3065                immutable: true,
3066                api_name: String::new(),
3067                optional: false,
3068                json_encoded: false,
3069                default_value: None,
3070                enum_values: None,
3071                read_path: None,
3072                update_only: false,
3073                ..Default::default()
3074            },
3075            IacAttribute {
3076                canonical_name: "access_expires".to_string(),
3077                description: "".to_string(),
3078                iac_type: IacType::Integer,
3079                required: false,
3080                computed: false,
3081                sensitive: false,
3082                immutable: false,
3083                api_name: String::new(),
3084                optional: false,
3085                json_encoded: false,
3086                default_value: None,
3087                enum_values: None,
3088                read_path: None,
3089                update_only: false,
3090                ..Default::default()
3091            },
3092        ];
3093        let f = build_observe_func(&r, "AuthMethodApiKey", &ResourceShape::default(), &None);
3094        let body_decl = f.body.stmts.iter().find_map(|s| match s {
3095            GoStmt::ShortDecl { names, values } if names == &["body".to_string()] => Some(values),
3096            _ => None,
3097        }).expect("body short-decl present");
3098        let GoExpr::Composite { fields, .. } = &body_decl[0] else {
3099            panic!("expected composite literal for body");
3100        };
3101        let field_names: Vec<&str> = fields
3102            .iter()
3103            .filter_map(|(n, _)| n.as_deref())
3104            .collect();
3105        assert_eq!(field_names, vec!["Name", "Token"], "Read body must stay identifier-only");
3106    }
3107
3108    #[test]
3109    fn imports_include_required_runtime_packages() {
3110        let f = build_controller_file(
3111            &auth_method_api_key(),
3112            &akeyless_provider(),
3113            &ControllerConfig::akeyless_default(),
3114        );
3115        let paths: Vec<&str> = f.imports.iter().map(|i| i.path.as_str()).collect();
3116        // stdlib
3117        assert!(paths.contains(&"context"));
3118        assert!(paths.contains(&"errors"));
3119        assert!(paths.contains(&"time"));
3120        // crossplane-runtime
3121        assert!(paths.contains(&"github.com/crossplane/crossplane-runtime/apis/common/v1"));
3122        assert!(paths.contains(&"github.com/crossplane/crossplane-runtime/pkg/meta"));
3123        assert!(paths.contains(&"github.com/crossplane/crossplane-runtime/pkg/reconciler/managed"));
3124        assert!(paths.contains(&"github.com/crossplane/crossplane-runtime/pkg/resource"));
3125        // controller-runtime
3126        assert!(paths.contains(&"sigs.k8s.io/controller-runtime"));
3127        assert!(paths.contains(&"sigs.k8s.io/controller-runtime/pkg/client"));
3128        // sdk + types
3129        assert!(paths.contains(&"github.com/pleme-io/akeyless-go"));
3130        // No duplicate paths (would be a regression)
3131        let mut sorted = paths.clone();
3132        sorted.sort_unstable();
3133        sorted.dedup();
3134        assert_eq!(sorted.len(), paths.len(), "imports must be unique");
3135    }
3136
3137    #[test]
3138    fn imports_aliases_correct() {
3139        let f = build_controller_file(
3140            &auth_method_api_key(),
3141            &akeyless_provider(),
3142            &ControllerConfig::akeyless_default(),
3143        );
3144        let by_path: std::collections::HashMap<&str, Option<&str>> = f
3145            .imports
3146            .iter()
3147            .map(|i| (i.path.as_str(), i.alias.as_deref()))
3148            .collect();
3149        assert_eq!(
3150            by_path.get("github.com/crossplane/crossplane-runtime/apis/common/v1"),
3151            Some(&Some("xpv1"))
3152        );
3153        assert_eq!(
3154            by_path.get("sigs.k8s.io/controller-runtime"),
3155            Some(&Some("ctrl"))
3156        );
3157        assert_eq!(
3158            by_path.get("github.com/pleme-io/akeyless-go"),
3159            Some(&Some("akeyless"))
3160        );
3161    }
3162
3163    #[test]
3164    fn five_representative_resources_render_cleanly() {
3165        let provider = akeyless_provider();
3166        let cfg = ControllerConfig::akeyless_default();
3167        let resources = vec![auth_method_api_key(), role_no_update()];
3168        for r in &resources {
3169            let s = render_controller(r, &provider, &cfg);
3170            // Header
3171            assert!(
3172                s.starts_with("// Code generated by iac-forge. DO NOT EDIT."),
3173                "missing header in {}",
3174                r.name
3175            );
3176            // Each resource emits all 4 ExternalClient methods
3177            for m in &["Observe", "Create", "Update", "Delete"] {
3178                assert!(
3179                    s.contains(&format!("func (e *external) {m}")),
3180                    "missing {m} in {}",
3181                    r.name
3182                );
3183            }
3184            // No leakage
3185            assert!(!s.contains("{kind}"));
3186            assert!(!s.contains("{this_pkg}"));
3187        }
3188    }
3189
3190    #[test]
3191    fn no_method_body_panics_for_resources_with_or_without_update() {
3192        let cfg = ControllerConfig::akeyless_default();
3193        let provider = akeyless_provider();
3194        // With update endpoint
3195        let _ = render_controller(&auth_method_api_key(), &provider, &cfg);
3196        // Without update endpoint
3197        let _ = render_controller(&role_no_update(), &provider, &cfg);
3198    }
3199
3200    #[test]
3201    fn rendered_setup_chain_matches_expected_method_order() {
3202        // The Setup function returns a chain:
3203        //   ctrl.NewControllerManagedBy(mgr).Named(name).For(&v1alpha1.<Kind>{}).Complete(r)
3204        // Verify all four pieces are present in the rendered output, in
3205        // the right order.
3206        let s = render_controller(
3207            &auth_method_api_key(),
3208            &akeyless_provider(),
3209            &ControllerConfig::akeyless_default(),
3210        );
3211        let nc_pos = s.find("ctrl.NewControllerManagedBy(mgr)").unwrap();
3212        let named_pos = s.find(".Named(name)").unwrap();
3213        let for_pos = s.find(".For(&v1alpha1.AuthMethodApiKey{})").unwrap();
3214        let complete_pos = s.find(".Complete(r)").unwrap();
3215        assert!(nc_pos < named_pos);
3216        assert!(named_pos < for_pos);
3217        assert!(for_pos < complete_pos);
3218    }
3219}