stack-engine 0.9.1

Pure execution facade for Stack diagram operations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
//! Pure operation facade and output contract for Stack diagrams.
//!
//! The facade accepts source bytes and a validated, versioned theme catalog. It
//! never reads the filesystem, network, process environment, clock, locale, or
//! host font APIs. Invalid user source is returned as ordered diagnostics in a
//! successful operation result; [`OperationalError`] is reserved for failures
//! in supplied execution inputs or violated internal pipeline invariants.
//!
//! ```
//! use stack_engine::Engine;
//!
//! let engine = Engine::bundled();
//! let output = engine.check(b"stack 1.0 diagram \"API\" { node api \"API\" }")?;
//! assert!(output.diagnostics.is_empty());
//! assert_eq!(output.metadata.language_version.map(|version| version.major), Some(1));
//! # Ok::<(), stack_engine::OperationalError>(())
//! ```

#![forbid(unsafe_code)]
#![deny(missing_docs)]

use std::error::Error;
use std::fmt;

use stack_compiler::diagnostic as compiler_diagnostic;

mod labels;
mod resources;
mod routing;
mod scene;
mod svg;

#[cfg(test)]
mod layout_quality;

#[cfg(test)]
mod layout_congestion;

#[cfg(test)]
mod placement_quality;

mod language;
mod provider;
pub use language::{
    CompletionItem, CompletionKind, CompletionOutput, Hover, HoverKind, HoverOutput,
    LANGUAGE_INTELLIGENCE_SCHEMA_VERSION, TextEdit,
};
pub use provider::{ProviderAsset, ProviderPack};

/// Version of the Rust engine facade.
pub const ENGINE_VERSION: &str = env!("CARGO_PKG_VERSION");

/// Result channel for failures outside user-authored Stack source.
pub type OperationResult<T> = Result<T, OperationalError>;

/// Pure engine facade backed by one validated catalog and revision.
#[derive(Debug, Clone, Copy)]
pub struct Engine<'catalog> {
    catalog: &'catalog stack_theme::Catalog,
    catalog_revision: &'catalog str,
    provider_packs: &'catalog [ProviderPack],
}

#[derive(Debug)]
struct PreparedScene<'catalog> {
    scene: scene::Scene,
    resources: resources::Resources<'catalog>,
    diagnostics: Vec<Diagnostic>,
}

impl Engine<'static> {
    /// Creates an engine backed by the catalog embedded in `stack-theme`.
    #[must_use]
    pub fn bundled() -> Self {
        Self {
            catalog: stack_theme::catalog(),
            catalog_revision: stack_theme::CATALOG_REVISION,
            provider_packs: &[],
        }
    }
}

impl Default for Engine<'static> {
    fn default() -> Self {
        Self::bundled()
    }
}

impl<'catalog> Engine<'catalog> {
    /// Creates an engine backed by the bundled catalog and validated provider packs.
    ///
    /// Provider assets remain caller-owned in-memory data. The engine performs
    /// no discovery, file access, download, upload, caching, or terms decision.
    pub fn with_provider_packs(provider_packs: &'catalog [ProviderPack]) -> OperationResult<Self> {
        Self::with_catalog_and_provider_packs(
            stack_theme::catalog(),
            stack_theme::CATALOG_REVISION,
            provider_packs,
        )
    }

    /// Creates an engine from a previously validated catalog and its content revision.
    ///
    /// The catalog document must already have passed the public `stack-theme`
    /// schema and asset validator. This constructor checks the fallback records
    /// needed by every engine operation and rejects invalid execution input as an
    /// operational error rather than a user-source diagnostic.
    pub fn with_catalog(
        catalog: &'catalog stack_theme::Catalog,
        catalog_revision: &'catalog str,
    ) -> OperationResult<Self> {
        Self::with_catalog_and_provider_packs(catalog, catalog_revision, &[])
    }

    /// Creates an engine from a validated catalog and validated provider packs.
    ///
    /// Provider namespaces must be unique. Provider icons cannot replace core
    /// catalog identifiers because [`ProviderPack::new`] requires namespaced IDs.
    pub fn with_catalog_and_provider_packs(
        catalog: &'catalog stack_theme::Catalog,
        catalog_revision: &'catalog str,
        provider_packs: &'catalog [ProviderPack],
    ) -> OperationResult<Self> {
        if !valid_catalog_revision(catalog_revision) {
            return Err(OperationalError::InvalidCatalog {
                reason: "catalog revision must be a lowercase sha256 digest",
            });
        }
        if !catalog
            .themes
            .iter()
            .any(|theme| theme.id == catalog.fallbacks.missing_theme_id)
        {
            return Err(OperationalError::InvalidCatalog {
                reason: "missing-theme fallback does not reference an active theme",
            });
        }
        if catalog.themes.iter().any(|theme| {
            !theme
                .icons
                .iter()
                .any(|icon| icon.id == catalog.fallbacks.missing_icon_id)
        }) {
            return Err(OperationalError::InvalidCatalog {
                reason: "missing-icon fallback is not present in every theme",
            });
        }

        if provider_packs.len() > 32 {
            return Err(OperationalError::InvalidProviderPack {
                reason: "an engine may contain at most 32 provider packs",
            });
        }
        for (index, pack) in provider_packs.iter().enumerate() {
            if provider_packs[..index]
                .iter()
                .any(|candidate| candidate.manifest().provider.id == pack.manifest().provider.id)
            {
                return Err(OperationalError::InvalidProviderPack {
                    reason: "provider namespaces must be unique",
                });
            }
        }

        Ok(Self {
            catalog,
            catalog_revision,
            provider_packs,
        })
    }

    /// Formats source while preserving compiler diagnostics in authored order.
    pub fn format(&self, source: &[u8]) -> OperationResult<FormatOutput> {
        let formatted = stack_formatter::format_bytes(source);
        Ok(FormatOutput {
            formatted_source: formatted.source,
            diagnostics: portable_diagnostics(formatted.diagnostics),
            metadata: self.metadata(declared_language_version(source)),
        })
    }

    /// Runs compiler, theme, layout, and routing validation without producing SVG.
    pub fn check(&self, source: &[u8]) -> OperationResult<CheckOutput> {
        let compiled = stack_compiler::compile_bytes_with_source_map(source);
        let mut diagnostics = portable_diagnostics(compiled.diagnostics);
        if let Some(diagram) = &compiled.diagram {
            let source_map = compiled.source_map.as_ref().ok_or(
                OperationalError::InvalidIntermediateRepresentation {
                    reason: "compiler omitted the source map for normalized IR",
                },
            )?;
            diagnostics.extend(self.prepare_scene(diagram, source_map)?.diagnostics);
        }
        Ok(CheckOutput {
            diagnostics,
            metadata: self.metadata(declared_language_version(source)),
        })
    }

    /// Produces a deterministic standalone SVG from valid Stack source.
    ///
    /// Invalid source returns a normal [`RenderOutput`] with ordered diagnostics
    /// and no SVG. Resource and layout warnings preserve a fallback SVG, while
    /// invalid catalog or intermediate pipeline state uses [`OperationalError`].
    pub fn render(&self, source: &[u8]) -> OperationResult<RenderOutput> {
        let compiled = stack_compiler::compile_bytes_with_source_map(source);
        let metadata = self.metadata(declared_language_version(source));
        if compiled.diagram.is_none() {
            return Ok(RenderOutput {
                svg: None,
                diagnostics: portable_diagnostics(compiled.diagnostics),
                metadata,
                provider_notices: Vec::new(),
            });
        }

        let diagram = compiled.diagram.as_ref().ok_or(
            OperationalError::InvalidIntermediateRepresentation {
                reason: "compiler omitted normalized IR after successful compilation",
            },
        )?;
        let source_map = compiled.source_map.as_ref().ok_or(
            OperationalError::InvalidIntermediateRepresentation {
                reason: "compiler omitted the source map for normalized IR",
            },
        )?;
        let prepared = self.prepare_scene(diagram, source_map)?;
        let mut diagnostics = portable_diagnostics(compiled.diagnostics);
        diagnostics.extend(prepared.diagnostics);
        let svg = svg::render(diagram, &prepared.scene, &prepared.resources, &metadata).map_err(
            |error| OperationalError::InvalidIntermediateRepresentation {
                reason: error.reason(),
            },
        )?;
        Ok(RenderOutput {
            svg: Some(svg),
            diagnostics,
            metadata,
            provider_notices: prepared.resources.provider_notices(),
        })
    }

    fn metadata(&self, language_version: Option<LanguageVersion>) -> EngineMetadata {
        EngineMetadata {
            engine_version: ENGINE_VERSION.to_owned(),
            language_version,
            theme_catalog_version: self.catalog.catalog_version.clone(),
            theme_catalog_revision: self.catalog_revision.to_owned(),
        }
    }

    fn prepare_scene(
        &self,
        diagram: &stack_compiler::ir::Diagram,
        source_map: &stack_compiler::source_map::SourceMap,
    ) -> OperationResult<PreparedScene<'catalog>> {
        let resources = resources::Resources::resolve(diagram, self.catalog, self.provider_packs)
            .map_err(|error| OperationalError::InvalidCatalog {
            reason: error.reason(),
        })?;
        let scene = scene::layout(diagram, self.catalog).map_err(|error| {
            OperationalError::InvalidIntermediateRepresentation {
                reason: error.reason(),
            }
        })?;
        if !scene.geometry_is_valid() {
            return Err(OperationalError::InvalidIntermediateRepresentation {
                reason: "layout produced invalid containment or overlap geometry",
            });
        }
        let mut diagnostics = resources
            .warnings
            .iter()
            .map(|warning| resource_diagnostic(warning, source_map))
            .collect::<OperationResult<Vec<_>>>()?;
        diagnostics.extend(
            scene
                .unsatisfied_orders
                .iter()
                .map(|scope| order_diagnostic(scope, source_map))
                .collect::<OperationResult<Vec<_>>>()?,
        );
        Ok(PreparedScene {
            scene,
            resources,
            diagnostics,
        })
    }
}

fn resource_diagnostic(
    warning: &resources::ResourceWarning,
    source_map: &stack_compiler::source_map::SourceMap,
) -> OperationResult<Diagnostic> {
    let (code, message, help, origin) = match warning {
        resources::ResourceWarning::MissingTheme(identifier) => (
            "STK6001",
            format!("theme '{identifier}' is unavailable; default theme was used"),
            "Install the requested theme or select an available theme.",
            source_map.theme(),
        ),
        resources::ResourceWarning::MissingIcon { node_id, icon_id } => (
            "STK5001",
            format!("icon '{icon_id}' is unavailable; the missing-icon fallback was used"),
            "Install the icon in the effective theme or remove the icon property.",
            source_map.node_icon(node_id).ok_or(
                OperationalError::InvalidIntermediateRepresentation {
                    reason: "source map omitted a normalized node",
                },
            )?,
        ),
    };
    let span = origin
        .span()
        .ok_or(OperationalError::InvalidIntermediateRepresentation {
            reason: "source map omitted an authored resource identifier",
        })?;
    Ok(Diagnostic {
        code: code.to_owned(),
        severity: Severity::Warning,
        message,
        range: SourceRange::from(span),
        expected: Vec::new(),
        help: Some(help.to_owned()),
        related: Vec::new(),
    })
}

fn order_diagnostic(
    scope: &scene::SceneScope,
    source_map: &stack_compiler::source_map::SourceMap,
) -> OperationResult<Diagnostic> {
    let origin = match scope {
        scene::SceneScope::Diagram => source_map.diagram_order(),
        scene::SceneScope::Group(identifier) => source_map.group_order(identifier).ok_or(
            OperationalError::InvalidIntermediateRepresentation {
                reason: "source map omitted a normalized group",
            },
        )?,
    };
    let span = origin
        .span()
        .ok_or(OperationalError::InvalidIntermediateRepresentation {
            reason: "source map omitted an authored order hint",
        })?;
    Ok(Diagnostic {
        code: "STK4001".to_owned(),
        severity: Severity::Warning,
        message: "order hint could not be satisfied by deterministic layout".to_owned(),
        range: SourceRange::from(span),
        expected: Vec::new(),
        help: Some("Adjust the order hint or same-rank constraints.".to_owned()),
        related: Vec::new(),
    })
}

/// Failure in execution inputs or internal pipeline invariants, not in Stack source.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum OperationalError {
    /// A provided catalog violates an invariant required by pure execution.
    InvalidCatalog {
        /// Stable explanation of the violated catalog invariant.
        reason: &'static str,
    },
    /// A provider pack violates safe deterministic rendering invariants.
    InvalidProviderPack {
        /// Stable explanation of the violated provider-pack invariant.
        reason: &'static str,
    },
    /// A language-intelligence request violates its stateless input contract.
    InvalidLanguageIntelligenceInput {
        /// Stable explanation of the invalid source position or completion catalog.
        reason: &'static str,
    },
    /// Compiler or layout data violates an invariant required by pure execution.
    InvalidIntermediateRepresentation {
        /// Stable explanation of the violated invariant.
        reason: &'static str,
    },
}

impl fmt::Display for OperationalError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidCatalog { reason } => write!(formatter, "invalid theme catalog: {reason}"),
            Self::InvalidProviderPack { reason } => {
                write!(formatter, "invalid provider pack: {reason}")
            }
            Self::InvalidLanguageIntelligenceInput { reason } => {
                write!(formatter, "invalid language-intelligence input: {reason}")
            }
            Self::InvalidIntermediateRepresentation { reason } => {
                write!(formatter, "invalid intermediate representation: {reason}")
            }
        }
    }
}

impl Error for OperationalError {}

/// Version metadata attached to every operation output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EngineMetadata {
    /// Semantic version of `stack-engine`.
    pub engine_version: String,
    /// Authored language version, absent when decoding or syntax parsing fails.
    pub language_version: Option<LanguageVersion>,
    /// Semantic version of the selected theme catalog.
    pub theme_catalog_version: String,
    /// Content revision of the selected theme catalog and icon bytes.
    pub theme_catalog_revision: String,
}

/// Authored Stack language version when decoding and syntax parsing succeed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LanguageVersion {
    /// Authored major language version.
    pub major: u32,
    /// Authored minor language version.
    pub minor: u32,
}

/// Result of the format operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FormatOutput {
    /// Canonical source, absent after encoding, lexical, or syntax failure.
    pub formatted_source: Option<String>,
    /// Compiler diagnostics in deterministic authored order.
    pub diagnostics: Vec<Diagnostic>,
    /// Versions that identify the exact operation implementation and inputs.
    pub metadata: EngineMetadata,
}

/// Result of the check operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CheckOutput {
    /// Compiler, theme, and layout diagnostics in deterministic order.
    pub diagnostics: Vec<Diagnostic>,
    /// Versions that identify the exact operation implementation and inputs.
    pub metadata: EngineMetadata,
}

/// Result of the render operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenderOutput {
    /// Standalone SVG, absent whenever an error diagnostic prevents rendering.
    pub svg: Option<String>,
    /// Compiler, theme, and layout diagnostics in deterministic order.
    pub diagnostics: Vec<Diagnostic>,
    /// Versions that identify the exact operation implementation and inputs.
    pub metadata: EngineMetadata,
    /// Provider-specific notices for the exact assets embedded in this output.
    pub provider_notices: Vec<ProviderNotice>,
}

/// Notice and provenance for one provider pack used by a rendered artifact.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProviderNotice {
    /// Stable provider namespace.
    pub provider_id: String,
    /// Human-readable provider name.
    pub provider_name: String,
    /// Provider-pack semantic version.
    pub pack_version: String,
    /// Deterministic hash of the manifest and processed asset bytes.
    pub pack_revision: String,
    /// Audited upstream release identifier.
    pub source_release: String,
    /// Complete official source archive SHA-256.
    pub archive_sha256: String,
    /// Provider terms reviewed for this pack.
    pub terms_url: String,
    /// Every audited archive that contributed an icon to this pack.
    pub sources: Vec<ProviderNoticeSource>,
    /// User-visible attribution text.
    pub attribution: String,
    /// User-visible terms summary.
    pub terms_summary: String,
    /// User-visible non-endorsement statement.
    pub non_endorsement: String,
    /// Exact provider icons embedded in the output.
    pub icons: Vec<ProviderNoticeIcon>,
}

/// One provider icon listed in a rendered-artifact notice.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProviderNoticeIcon {
    /// Namespaced provider icon identifier.
    pub id: String,
    /// Official provider product name.
    pub product_name: String,
    /// Rights-owner source for this brand icon, when the archive is multi-brand.
    pub brand_source_url: Option<String>,
    /// Rights-owner usage guidelines for this brand icon, when available.
    pub brand_guidelines_url: Option<String>,
    /// Pack-local source ID, or `primary` for the primary source.
    pub source_id: String,
}

/// One audited archive listed in a rendered-artifact notice.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProviderNoticeSource {
    /// Pack-local source ID. The primary source always uses `primary`.
    pub id: String,
    /// Official source page.
    pub page_url: String,
    /// Audited upstream release identifier.
    pub release: String,
    /// Complete official source archive SHA-256.
    pub archive_sha256: String,
    /// Terms reviewed for this source.
    pub terms_url: String,
}

/// Engine-owned portable diagnostic shared by native and future WASM outputs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Diagnostic {
    /// Stable Stack diagnostic identifier.
    pub code: String,
    /// Whether the diagnostic prevents an artifact from being produced.
    pub severity: Severity,
    /// Concise human-readable diagnostic description.
    pub message: String,
    /// Primary end-exclusive source range.
    pub range: SourceRange,
    /// Ordered source values or constructs valid at the primary range.
    pub expected: Vec<String>,
    /// Optional corrective guidance.
    pub help: Option<String>,
    /// Other source locations involved in the diagnostic.
    pub related: Vec<RelatedInformation>,
}

/// Severity of one portable diagnostic.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
    /// Prevents normalized or rendered output as defined by the operation.
    Error,
    /// Preserves successful output while reporting actionable information.
    Warning,
}

/// Additional source context related to a diagnostic.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RelatedInformation {
    /// Description of the related source location.
    pub message: String,
    /// End-exclusive related source range.
    pub range: SourceRange,
}

/// End-exclusive source range.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SourceRange {
    /// Inclusive source position.
    pub start: SourcePosition,
    /// Exclusive source position.
    pub end: SourcePosition,
}

/// One-based line and column with a zero-based UTF-8 byte offset.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SourcePosition {
    /// Zero-based UTF-8 byte offset.
    pub byte_offset: u64,
    /// One-based source line.
    pub line: u64,
    /// One-based Unicode scalar column.
    pub column: u64,
}

fn valid_catalog_revision(revision: &str) -> bool {
    revision.strip_prefix("sha256:").is_some_and(|digest| {
        digest.len() == 64
            && digest
                .bytes()
                .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
    })
}

fn declared_language_version(source: &[u8]) -> Option<LanguageVersion> {
    stack_compiler::parse_bytes(source)
        .document
        .map(|document| LanguageVersion {
            major: document.version.major,
            minor: document.version.minor,
        })
}

fn portable_diagnostics(diagnostics: Vec<compiler_diagnostic::Diagnostic>) -> Vec<Diagnostic> {
    diagnostics.into_iter().map(Diagnostic::from).collect()
}

impl From<compiler_diagnostic::Diagnostic> for Diagnostic {
    fn from(diagnostic: compiler_diagnostic::Diagnostic) -> Self {
        Self {
            code: diagnostic.code.to_owned(),
            severity: match diagnostic.severity {
                compiler_diagnostic::Severity::Error => Severity::Error,
                compiler_diagnostic::Severity::Warning => Severity::Warning,
            },
            message: diagnostic.message,
            range: SourceRange::from(diagnostic.span),
            expected: diagnostic.expected,
            help: diagnostic.help,
            related: diagnostic
                .related
                .into_iter()
                .map(|related| RelatedInformation {
                    message: related.message,
                    range: SourceRange::from(related.span),
                })
                .collect(),
        }
    }
}

impl From<compiler_diagnostic::Span> for SourceRange {
    fn from(span: compiler_diagnostic::Span) -> Self {
        Self {
            start: SourcePosition::from(span.start),
            end: SourcePosition::from(span.end),
        }
    }
}

impl From<compiler_diagnostic::SourcePosition> for SourcePosition {
    fn from(position: compiler_diagnostic::SourcePosition) -> Self {
        Self {
            byte_offset: position.byte_offset as u64,
            line: position.line as u64,
            column: position.column as u64,
        }
    }
}

#[cfg(test)]
mod tests {
    use std::error::Error;

    use stack_compiler::diagnostic as compiler_diagnostic;

    use super::{
        Diagnostic, ENGINE_VERSION, Engine, LanguageVersion, OperationalError, Severity,
        SourcePosition,
    };

    const VALID_SOURCE: &[u8] = b"stack 1.0 diagram \"API\" { node api \"API\" }";

    #[test]
    fn valid_wide_connectors_render_labelled_edges_in_both_directions() -> Result<(), Box<dyn Error>>
    {
        for width in [1_500, 15_000, 15_998, 15_999, 16_000, 32_000] {
            let mut catalog = stack_theme::catalog().clone();
            for theme in &mut catalog.themes {
                theme.connector.width_milli_px = width;
            }
            let engine = Engine::with_catalog(&catalog, stack_theme::CATALOG_REVISION)?;
            for direction in ["right", "down"] {
                let source = format!(
                    "stack 1.0 diagram \"Wide stroke\" {{ layout {{ direction {direction} }} node a \"A\" node b \"B\" edge a -> b \"Request\" }}"
                );
                let output = engine.render(source.as_bytes())?;
                assert!(
                    output.diagnostics.is_empty(),
                    "width={width}, direction={direction}"
                );
                assert!(
                    output
                        .svg
                        .ok_or("missing wide-stroke SVG")?
                        .contains("data-edge-label=\"Request\"")
                );
            }
        }
        Ok(())
    }

    #[test]
    fn bundled_engine_reports_all_version_metadata() {
        let engine = Engine::bundled();
        let result = engine.check(VALID_SOURCE);
        assert!(result.is_ok());
        if let Ok(output) = result {
            assert!(output.diagnostics.is_empty());
            assert_eq!(output.metadata.engine_version, ENGINE_VERSION);
            assert_eq!(
                output.metadata.language_version,
                Some(LanguageVersion { major: 1, minor: 0 })
            );
            assert_eq!(output.metadata.theme_catalog_version, "0.7.0");
            assert_eq!(
                output.metadata.theme_catalog_revision,
                stack_theme::CATALOG_REVISION
            );
            assert_eq!(Engine::default().check(VALID_SOURCE), Ok(output));
        }
    }

    #[test]
    fn bundled_catalog_resolves_explicit_core_icons() -> Result<(), Box<dyn Error>> {
        let expected_icons = [
            ("api", "Application programming interface"),
            ("web", "Web application"),
            ("mobile", "Mobile application"),
            ("desktop", "Desktop application"),
            ("server", "Server host"),
            ("container", "Application container"),
            ("cluster", "Compute cluster"),
            ("cloud", "Cloud environment"),
            ("scheduler", "Scheduled execution"),
            ("webhook", "Webhook endpoint"),
            ("identity", "Identity and access"),
            ("observability", "Observability system"),
            ("gateway", "Network gateway"),
            ("load-balancer", "Load balancer"),
            ("dns", "Domain name service"),
            ("cdn", "Content delivery network"),
            ("firewall", "Network firewall"),
            ("network", "Network topology"),
            ("event", "Discrete event"),
            ("stream", "Event stream"),
            ("search", "Search service"),
            ("analytics", "Analytics system"),
            ("repository", "Source code repository"),
            ("pipeline", "Delivery pipeline"),
            ("secret", "Secret or credential"),
            ("document", "Document or knowledge base"),
            ("task", "Task or issue tracker"),
            ("chat", "Chat or messaging tool"),
            ("email", "Email delivery"),
            ("ai", "Artificial intelligence system"),
        ];
        let catalog = stack_theme::catalog();
        assert_eq!(catalog.catalog_version, "0.7.0");
        assert_eq!(
            stack_theme::CATALOG_REVISION,
            "sha256:4a8b94b746c6b120998bfbe701edd722449a28c89c424b0a33f67561756ded5a"
        );
        for theme in &catalog.themes {
            for (identifier, subject) in expected_icons {
                let icon = theme
                    .icons
                    .iter()
                    .find(|icon| icon.id == identifier)
                    .ok_or("core icon is unavailable in a bundled theme")?;
                assert_eq!(icon.subject, subject);
                assert_eq!(icon.asset.path, format!("assets/core/{identifier}.svg"));
            }
        }

        let source = b"stack 1.0 diagram \"Core icon\" { theme dark node gateway \"Gateway\" { kind service detail \"Public API\" icon \"gateway\" } }";
        let checked = Engine::bundled().check(source)?;
        let rendered = Engine::bundled().render(source)?;
        assert!(checked.diagnostics.is_empty());
        assert!(rendered.diagnostics.is_empty());
        assert_eq!(rendered.metadata.theme_catalog_version, "0.7.0");
        assert_eq!(
            rendered.metadata.theme_catalog_revision,
            stack_theme::CATALOG_REVISION
        );
        let svg = rendered.svg.ok_or("explicit icon render produced no SVG")?;
        assert!(svg.contains("data-icon-id=\"gateway\""));
        assert!(!svg.contains("data-icon-id=\"kind-external\""));
        Ok(())
    }

    #[test]
    fn format_preserves_semantic_diagnostics_but_not_syntax_failures() {
        let engine = Engine::bundled();
        let semantic_error = b"stack 1.0 diagram \"API\" { node api \"A\" node api \"B\" }";
        let semantic_result = engine.format(semantic_error);
        assert!(semantic_result.is_ok());
        if let Ok(semantic) = semantic_result {
            assert!(semantic.formatted_source.is_some());
            assert!(!semantic.diagnostics.is_empty());
        }

        let encoding_result = engine.format(b"stack 1.0\n\xff");
        assert!(encoding_result.is_ok());
        if let Ok(encoding) = encoding_result {
            assert!(encoding.formatted_source.is_none());
            assert_eq!(encoding.diagnostics[0].code, "STK1001");
            assert_eq!(encoding.metadata.language_version, None);
        }
    }

    #[test]
    fn check_keeps_compiler_diagnostic_order_and_positions() {
        let source =
            b"stack 1.0 diagram \"API\" { node api \"A\" node api \"B\" edge api -> missing }";
        let expected = stack_compiler::compile_bytes(source)
            .diagnostics
            .into_iter()
            .map(|diagnostic| diagnostic.code)
            .collect::<Vec<_>>();
        let result = Engine::bundled().check(source);
        assert!(result.is_ok());
        if let Ok(output) = result {
            assert_eq!(
                output
                    .diagnostics
                    .iter()
                    .map(|diagnostic| diagnostic.code.as_str())
                    .collect::<Vec<_>>(),
                expected
            );
            assert!(
                output
                    .diagnostics
                    .windows(2)
                    .all(|pair| pair[0].range.start.byte_offset <= pair[1].range.start.byte_offset)
            );
        }
    }

    #[test]
    fn check_emits_order_warning_at_the_authored_statement() -> Result<(), Box<dyn Error>> {
        let source = "stack 1.0 diagram \"Order\" { layout { direction right order [b, a] } node a \"A\" node b \"B\" }";
        let output = Engine::bundled().check(source.as_bytes())?;
        assert_eq!(output.diagnostics.len(), 1);
        let diagnostic = &output.diagnostics[0];
        assert_eq!(diagnostic.code, "STK4001");
        assert_eq!(diagnostic.severity, Severity::Warning);
        let start = source
            .find("order [b, a]")
            .ok_or("missing order statement")?;
        let end = start + "order [b, a]".len();
        assert_eq!(diagnostic.range.start.byte_offset, start as u64);
        assert_eq!(diagnostic.range.end.byte_offset, end as u64);
        assert_eq!(diagnostic.range.start.line, 1);
        assert_eq!(diagnostic.range.start.column, start as u64 + 1);
        assert_eq!(diagnostic.range.end.column, end as u64 + 1);
        Ok(())
    }

    #[test]
    fn check_omits_order_warning_when_rank_placement_satisfies_it() -> Result<(), Box<dyn Error>> {
        let source = b"stack 1.0 diagram \"Order\" { layout { direction right rank same [a, b] order [b, a] } node a \"A\" node b \"B\" }";
        let output = Engine::bundled().check(source)?;
        assert!(output.diagnostics.is_empty());
        Ok(())
    }

    #[test]
    fn group_order_warning_uses_the_group_source_map_entry() -> Result<(), Box<dyn Error>> {
        let source = "stack 1.0 diagram \"Group order\" { group pair \"Pair\" { layout { direction down order [b, a] } node a \"A\" node b \"B\" } }";
        let output = Engine::bundled().check(source.as_bytes())?;
        assert_eq!(output, Engine::bundled().check(source.as_bytes())?);
        assert_eq!(
            output
                .diagnostics
                .iter()
                .map(|diagnostic| diagnostic.code.as_str())
                .collect::<Vec<_>>(),
            vec!["STK4001"]
        );
        let start = source
            .find("order [b, a]")
            .ok_or("missing order statement")?;
        assert_eq!(output.diagnostics[0].range.start.byte_offset, start as u64);
        Ok(())
    }

    #[test]
    fn layout_warnings_follow_compiler_warnings() -> Result<(), Box<dyn Error>> {
        let mut source = String::from(
            "stack 1.0 diagram \"Warnings\" { layout { direction right order [hub, n0] } node hub \"Hub\" ",
        );
        for index in 0..13 {
            source.push_str(&format!(
                "node n{index} \"N {index}\" edge hub -> n{index} "
            ));
        }
        source.push('}');
        let output = Engine::bundled().check(source.as_bytes())?;
        assert_eq!(
            output
                .diagnostics
                .iter()
                .map(|diagnostic| diagnostic.code.as_str())
                .collect::<Vec<_>>(),
            vec!["STK4002", "STK4001"]
        );
        Ok(())
    }

    #[test]
    fn resource_fallbacks_report_authored_ranges_and_render_svg() -> Result<(), Box<dyn Error>> {
        let source = "stack 1.0 diagram \"Fallbacks\" { theme neon layout { direction right order [b, a] } node a \"A\" { icon \"missing\" } node b \"B\" }";
        let checked = Engine::bundled().check(source.as_bytes())?;
        let rendered = Engine::bundled().render(source.as_bytes())?;
        assert_eq!(checked.diagnostics, rendered.diagnostics);
        assert_eq!(
            rendered
                .diagnostics
                .iter()
                .map(|diagnostic| diagnostic.code.as_str())
                .collect::<Vec<_>>(),
            vec!["STK6001", "STK5001", "STK4001"]
        );

        let theme_start = source.find("neon").ok_or("missing theme identifier")?;
        assert_eq!(
            rendered.diagnostics[0].range.start.byte_offset,
            theme_start as u64
        );
        assert_eq!(
            rendered.diagnostics[0].range.end.byte_offset,
            (theme_start + "neon".len()) as u64
        );
        let icon_start = source.find("\"missing\"").ok_or("missing icon string")?;
        assert_eq!(
            rendered.diagnostics[1].range.start.byte_offset,
            icon_start as u64
        );
        assert_eq!(
            rendered.diagnostics[1].range.end.byte_offset,
            (icon_start + "\"missing\"".len()) as u64
        );
        let svg = rendered.svg.ok_or("render produced no SVG")?;
        assert!(svg.contains("data-theme-id=\"default\""));
        assert!(svg.contains("data-icon-id=\"kind-external\""));
        Ok(())
    }

    #[test]
    fn render_is_repeatable_and_escapes_source_text() -> Result<(), Box<dyn Error>> {
        let source = b"stack 1.0 diagram \"<script>&\" { node client \"\\\" onload=\\\"alert(1)<&>\" edge client -> api \"javascript:alert(1)\" node api \"API\" }";
        let first = Engine::bundled().render(source)?;
        let second = Engine::bundled().render(source)?;
        assert_eq!(first, second);
        let svg = first.svg.ok_or("render produced no SVG")?;
        assert!(svg.contains("&lt;script&gt;&amp;"));
        assert!(svg.contains("&quot; onload=&quot;alert(1)&lt;&amp;&gt;"));
        assert!(!svg.contains("<script"));
        assert!(!svg.contains("href="));
        Ok(())
    }

    #[cfg(feature = "conformance")]
    #[test]
    fn canonical_valid_fixtures_render_standalone_svg() -> Result<(), Box<dyn Error>> {
        let specification = std::env::var("STACK_SPECIFICATION_DIR")?;
        let valid_root = std::path::Path::new(&specification).join("conformance/valid");
        let mut cases = std::fs::read_dir(&valid_root)?.collect::<Result<Vec<_>, _>>()?;
        cases.sort_by_key(|entry| entry.file_name());
        if cases.is_empty() {
            return Err(format!("no valid fixtures found in {}", valid_root.display()).into());
        }

        for case in cases {
            let source_path = case.path().join("source.stack");
            if !source_path.is_file() {
                continue;
            }
            let output = Engine::bundled().render(&std::fs::read(&source_path)?)?;
            if output
                .diagnostics
                .iter()
                .any(|diagnostic| diagnostic.severity == Severity::Error)
            {
                return Err(
                    format!("{} produced an error diagnostic", source_path.display()).into(),
                );
            }
            let svg = output
                .svg
                .ok_or_else(|| format!("{} produced no standalone SVG", source_path.display()))?;
            assert!(svg.starts_with("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"));
            assert!(svg.ends_with("</svg>\n"));
        }
        Ok(())
    }

    #[test]
    fn render_separates_invalid_input_from_success() -> Result<(), Box<dyn Error>> {
        let engine = Engine::bundled();
        let result = engine.render(b"\xff");
        assert!(result.is_ok());
        if let Ok(output) = result {
            assert!(output.svg.is_none());
            assert_eq!(output.diagnostics[0].code, "STK1001");
            assert_eq!(output.metadata.language_version, None);
        }

        let output = engine.render(VALID_SOURCE)?;
        assert!(output.diagnostics.is_empty());
        assert!(
            output
                .svg
                .as_deref()
                .is_some_and(|svg| svg.contains("<svg"))
        );
        Ok(())
    }

    #[test]
    fn provided_catalog_requires_usable_fallbacks_and_revision() {
        let catalog = stack_theme::catalog().clone();
        assert!(Engine::with_catalog(&catalog, stack_theme::CATALOG_REVISION).is_ok());
        assert!(matches!(
            Engine::with_catalog(&catalog, "sha256:NOT-A-DIGEST"),
            Err(OperationalError::InvalidCatalog { .. })
        ));

        let mut missing_theme = catalog.clone();
        missing_theme.fallbacks.missing_theme_id = "missing".to_owned();
        assert!(matches!(
            Engine::with_catalog(&missing_theme, stack_theme::CATALOG_REVISION),
            Err(OperationalError::InvalidCatalog { .. })
        ));

        let mut missing_icon = catalog;
        missing_icon.fallbacks.missing_icon_id = "missing".to_owned();
        assert!(matches!(
            Engine::with_catalog(&missing_icon, stack_theme::CATALOG_REVISION),
            Err(OperationalError::InvalidCatalog { .. })
        ));
    }

    #[test]
    fn diagnostic_conversion_keeps_expected_help_and_related_ranges() {
        let start = compiler_diagnostic::SourcePosition {
            byte_offset: 3,
            line: 2,
            column: 4,
        };
        let end = compiler_diagnostic::SourcePosition {
            byte_offset: 7,
            line: 2,
            column: 8,
        };
        let diagnostic = compiler_diagnostic::Diagnostic {
            code: "STK4002",
            severity: compiler_diagnostic::Severity::Warning,
            message: "warning".to_owned(),
            span: compiler_diagnostic::Span { start, end },
            expected: vec!["right".to_owned(), "down".to_owned()],
            help: Some("help".to_owned()),
            related: vec![compiler_diagnostic::RelatedInformation {
                message: "related".to_owned(),
                span: compiler_diagnostic::Span::point(start),
            }],
        };

        let portable = Diagnostic::from(diagnostic);
        assert_eq!(portable.severity, Severity::Warning);
        assert_eq!(portable.expected, ["right", "down"]);
        assert_eq!(portable.help.as_deref(), Some("help"));
        assert_eq!(portable.related[0].message, "related");
        assert_eq!(
            portable.range.start,
            SourcePosition {
                byte_offset: 3,
                line: 2,
                column: 4,
            }
        );
    }

    #[test]
    fn operational_error_messages_are_stable() {
        assert_eq!(
            OperationalError::InvalidCatalog { reason: "reason" }.to_string(),
            "invalid theme catalog: reason"
        );
        assert_eq!(
            OperationalError::InvalidIntermediateRepresentation { reason: "reason" }.to_string(),
            "invalid intermediate representation: reason"
        );
        assert_eq!(
            OperationalError::InvalidProviderPack { reason: "reason" }.to_string(),
            "invalid provider pack: reason"
        );
        assert_eq!(
            OperationalError::InvalidLanguageIntelligenceInput { reason: "reason" }.to_string(),
            "invalid language-intelligence input: reason"
        );
    }
}