stygian-graph 0.9.2

High-performance graph-based web scraping engine with AI extraction, multi-modal support, and anti-bot capabilities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
//! Intelligent schema discovery service
//!
//! Automatically infers JSON Schema definitions from:
//! 1. **JSON/object examples** — type-inspects values to generate schema
//! 2. **HTML content** — uses an AI provider to suggest extraction schemas
//! 3. **User corrections** — applies overrides stored in a correction map
//! 4. **Evolution detection** — compares new inferences against cached schemas
//!
//! The service sits in the application layer and depends on `AIProvider` for
//! LLM-assisted HTML schema inference.
//!
//! # Example
//!
//! ```no_run
//! use stygian_graph::application::schema_discovery::{SchemaDiscoveryService, SchemaDiscoveryConfig};
//! use serde_json::json;
//!
//! # tokio::runtime::Runtime::new().unwrap().block_on(async {
//! let service = SchemaDiscoveryService::new(SchemaDiscoveryConfig::default(), None);
//!
//! // Infer from a JSON example
//! let example = json!({"name": "Alice", "age": 30, "active": true});
//! let schema = service.infer_from_example(&example);
//! assert_eq!(schema["type"].as_str().unwrap(), "object");
//! # });
//! ```

use std::collections::HashMap;
use std::sync::Arc;

use parking_lot::RwLock;
use serde_json::{Map, Value, json};
use tracing::debug;

/// Full standard GraphQL introspection query (6-level `ofType` depth for Relay
/// connection types such as `NON_NULL(LIST(NON_NULL(OBJECT)))`).
const INTROSPECTION_QUERY: &str = r"
query IntrospectionQuery {
  __schema {
    queryType { name }
    mutationType { name }
    subscriptionType { name }
    types { ...FullType }
    directives {
      name description locations
      args { ...InputValue }
    }
  }
}
fragment FullType on __Type {
  kind name description
  fields(includeDeprecated: true) {
    name description
    args { ...InputValue }
    type { ...TypeRef }
    isDeprecated deprecationReason
  }
  inputFields { ...InputValue }
  interfaces { ...TypeRef }
  enumValues(includeDeprecated: true) {
    name description isDeprecated deprecationReason
  }
  possibleTypes { ...TypeRef }
}
fragment InputValue on __InputValue {
  name description
  type { ...TypeRef }
  defaultValue
}
fragment TypeRef on __Type {
  kind name
  ofType {
    kind name
    ofType {
      kind name
      ofType {
        kind name
        ofType {
          kind name
          ofType {
            kind name
            ofType { kind name }
          }
        }
      }
    }
  }
}
";

use crate::domain::error::{ProviderError, Result, ServiceError, StygianError};
use crate::ports::{AIProvider, GraphQlAuth, ScrapingService, ServiceInput};

/// Discovered schema with metadata
#[derive(Debug, Clone)]
pub struct DiscoveredSchema {
    /// The JSON Schema object
    pub schema: Value,
    /// How the schema was derived
    pub source: SchemaSource,
    /// Confidence score [0.0, 1.0]
    pub confidence: f32,
    /// URL pattern or domain the schema is associated with
    pub url_pattern: Option<String>,
}

/// How a schema was derived
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SchemaSource {
    /// Inferred by type-inspecting a JSON example
    ExampleInference,
    /// Generated by an AI provider analysing HTML structure
    AiInference,
    /// Loaded from cache
    Cached,
    /// Manually supplied / corrected by user
    UserCorrection,
}

/// Configuration for the schema discovery service
#[derive(Debug, Clone)]
pub struct SchemaDiscoveryConfig {
    /// Maximum HTML content length sent to AI provider
    pub max_content_chars: usize,
    /// Cache discovered schemas by URL pattern
    pub cache_schemas: bool,
    /// Minimum confidence to accept an AI-inferred schema
    pub min_ai_confidence: f32,
}

impl Default for SchemaDiscoveryConfig {
    fn default() -> Self {
        Self {
            max_content_chars: 16_000,
            cache_schemas: true,
            min_ai_confidence: 0.6,
        }
    }
}

/// Schema evolution diff — describes changes between two schema versions
#[derive(Debug, Clone)]
pub struct SchemaDiff {
    /// Fields present in new schema but not in old
    pub added_fields: Vec<String>,
    /// Fields present in old schema but not in new
    pub removed_fields: Vec<String>,
    /// Fields whose type changed
    pub type_changes: Vec<(String, String, String)>, // (field, old_type, new_type)
    /// Whether schemas are considered compatible
    pub is_compatible: bool,
}

/// Intelligent schema discovery service
///
/// Infers JSON Schemas from content using local heuristics and an optional
/// AI provider. Maintains a schema cache for URL patterns and supports
/// user corrections.
pub struct SchemaDiscoveryService {
    config: SchemaDiscoveryConfig,
    /// Optional AI provider for HTML-to-schema inference
    ai_provider: Option<Arc<dyn AIProvider>>,
    /// Schema cache: `url_pattern` → [`DiscoveredSchema`]
    cache: Arc<RwLock<HashMap<String, DiscoveredSchema>>>,
    /// User correction map: `field_name` → corrected schema fragment
    corrections: Arc<RwLock<HashMap<String, Value>>>,
    /// Optional GraphQL scraping service for introspection
    graphql_service: Option<Arc<dyn ScrapingService>>,
}

impl SchemaDiscoveryService {
    /// Create a new schema discovery service
    ///
    /// # Example
    ///
    /// ```
    /// use stygian_graph::application::schema_discovery::{SchemaDiscoveryService, SchemaDiscoveryConfig};
    ///
    /// let service = SchemaDiscoveryService::new(SchemaDiscoveryConfig::default(), None);
    /// ```
    pub fn new(config: SchemaDiscoveryConfig, ai_provider: Option<Arc<dyn AIProvider>>) -> Self {
        Self {
            config,
            ai_provider,
            cache: Arc::new(RwLock::new(HashMap::new())),
            corrections: Arc::new(RwLock::new(HashMap::new())),
            graphql_service: None,
        }
    }

    /// Attach a GraphQL scraping service used by [`infer_from_graphql`](Self::infer_from_graphql).
    ///
    /// # Example
    ///
    /// ```no_run
    /// use stygian_graph::application::schema_discovery::{SchemaDiscoveryService, SchemaDiscoveryConfig};
    /// use stygian_graph::adapters::graphql::GraphQlService;
    /// use std::sync::Arc;
    ///
    /// let gql = Arc::new(GraphQlService::new(Default::default(), None));
    /// let svc = SchemaDiscoveryService::new(SchemaDiscoveryConfig::default(), None)
    ///     .with_graphql_service(gql);
    /// ```
    #[must_use]
    pub fn with_graphql_service(mut self, service: Arc<dyn ScrapingService>) -> Self {
        self.graphql_service = Some(service);
        self
    }

    /// Infer a JSON Schema by type-inspecting a JSON example value.
    ///
    /// Supports objects, arrays, strings, numbers, booleans, and null.
    ///
    /// # Example
    ///
    /// ```
    /// use stygian_graph::application::schema_discovery::{SchemaDiscoveryService, SchemaDiscoveryConfig};
    /// use serde_json::json;
    ///
    /// let svc = SchemaDiscoveryService::new(SchemaDiscoveryConfig::default(), None);
    /// let example = json!({"name": "Alice", "score": 9.5, "active": true});
    /// let schema = svc.infer_from_example(&example);
    ///
    /// assert_eq!(schema["type"].as_str().unwrap(), "object");
    /// assert_eq!(schema["properties"]["name"]["type"].as_str().unwrap(), "string");
    /// assert_eq!(schema["properties"]["score"]["type"].as_str().unwrap(), "number");
    /// ```
    pub fn infer_from_example(&self, example: &Value) -> Value {
        Self::infer_schema_for_value(example)
    }

    /// Recursively infer a JSON Schema for a single JSON value
    fn infer_schema_for_value(value: &Value) -> Value {
        match value {
            Value::Object(map) => {
                let mut properties = Map::new();
                let mut required = Vec::new();
                for (key, val) in map {
                    properties.insert(key.clone(), Self::infer_schema_for_value(val));
                    required.push(json!(key));
                }
                json!({
                    "type": "object",
                    "properties": Value::Object(properties),
                    "required": required
                })
            }
            Value::Array(items) => {
                // Infer item schema from first element
                let item_schema = items
                    .first()
                    .map_or_else(|| json!({}), Self::infer_schema_for_value);
                json!({
                    "type": "array",
                    "items": item_schema
                })
            }
            Value::String(_) => json!({"type": "string"}),
            Value::Number(n) => {
                if n.is_i64() || n.is_u64() {
                    json!({"type": "integer"})
                } else {
                    json!({"type": "number"})
                }
            }
            Value::Bool(_) => json!({"type": "boolean"}),
            Value::Null => json!({"type": "null"}),
        }
    }

    /// Infer a schema from HTML content using an AI provider.
    ///
    /// Returns an error if no AI provider is configured.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use stygian_graph::application::schema_discovery::{SchemaDiscoveryService, SchemaDiscoveryConfig};
    ///
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// let service = SchemaDiscoveryService::new(SchemaDiscoveryConfig::default(), None);
    /// // Without an AI provider, this returns Err
    /// let result = service.infer_from_html("<html>...</html>", None).await;
    /// assert!(result.is_err());
    /// # });
    /// ```
    pub async fn infer_from_html(
        &self,
        html: &str,
        url_pattern: Option<&str>,
    ) -> Result<DiscoveredSchema> {
        // Check cache first
        if self.config.cache_schemas
            && let Some(pattern) = url_pattern
        {
            let cache = self.cache.read();
            if let Some(cached) = cache.get(pattern) {
                debug!(pattern, "Schema cache hit");
                return Ok(DiscoveredSchema {
                    source: SchemaSource::Cached,
                    ..cached.clone()
                });
            }
        }

        let provider = self.ai_provider.as_ref().ok_or_else(|| {
            StygianError::Provider(ProviderError::ApiError(
                "No AI provider configured for HTML schema discovery".to_string(),
            ))
        })?;

        let truncated = if html.len() > self.config.max_content_chars {
            &html[..self.config.max_content_chars]
        } else {
            html
        };

        let discovery_schema = json!({
            "type": "object",
            "properties": {
                "schema": {
                    "type": "object",
                    "description": "A valid JSON Schema object describing the structured data in the HTML"
                },
                "confidence": {
                    "type": "number",
                    "minimum": 0.0,
                    "maximum": 1.0,
                    "description": "Confidence in the inferred schema [0.0, 1.0]"
                },
                "description": {
                    "type": "string",
                    "description": "Human-readable explanation of what data was detected"
                }
            },
            "required": ["schema", "confidence"]
        });

        let prompt = format!(
            "Analyze the following HTML page and infer a JSON Schema for the main structured \
             data it contains (e.g. product listings, articles, search results). \
             Return the schema definition.\n\nHTML:\n{truncated}"
        );

        let result = provider.extract(prompt, discovery_schema).await?;

        let schema = result
            .get("schema")
            .cloned()
            .unwrap_or_else(|| json!({"type": "object"}));

        #[allow(clippy::cast_possible_truncation)]
        let confidence = result
            .get("confidence")
            .and_then(Value::as_f64)
            .unwrap_or(0.7) as f32;

        // Apply any user corrections
        let schema = self.apply_corrections(schema);

        let discovered = DiscoveredSchema {
            schema,
            source: SchemaSource::AiInference,
            confidence,
            url_pattern: url_pattern.map(str::to_string),
        };

        // Cache the result
        if self.config.cache_schemas
            && let Some(pattern) = url_pattern
        {
            self.cache
                .write()
                .insert(pattern.to_string(), discovered.clone());
        }

        Ok(discovered)
    }

    /// Apply user corrections to an inferred schema
    fn apply_corrections(&self, mut schema: Value) -> Value {
        let corrections = self.corrections.read();
        if corrections.is_empty() {
            return schema;
        }

        if let Some(props) = schema.get_mut("properties").and_then(Value::as_object_mut) {
            for (field, correction) in corrections.iter() {
                if props.contains_key(field) {
                    props.insert(field.clone(), correction.clone());
                }
            }
        }
        schema
    }

    /// Register a user correction for a specific field type
    ///
    /// # Example
    ///
    /// ```
    /// use stygian_graph::application::schema_discovery::{SchemaDiscoveryService, SchemaDiscoveryConfig};
    /// use serde_json::json;
    ///
    /// let svc = SchemaDiscoveryService::new(SchemaDiscoveryConfig::default(), None);
    /// // Always use "integer" for "id" fields regardless of inferred type
    /// svc.add_correction("id".to_string(), json!({"type": "integer"}));
    /// ```
    pub fn add_correction(&self, field_name: String, schema_fragment: Value) {
        self.corrections.write().insert(field_name, schema_fragment);
    }

    /// Cache a schema for a URL pattern (useful for preloading known schemas)
    ///
    /// # Example
    ///
    /// ```
    /// use stygian_graph::application::schema_discovery::{SchemaDiscoveryService, SchemaDiscoveryConfig, SchemaSource};
    /// use serde_json::json;
    ///
    /// let svc = SchemaDiscoveryService::new(SchemaDiscoveryConfig::default(), None);
    /// svc.cache_schema(
    ///     "example.com/products".to_string(),
    ///     json!({"type": "object"}),
    ///     SchemaSource::UserCorrection,
    ///     1.0,
    /// );
    /// ```
    pub fn cache_schema(
        &self,
        url_pattern: String,
        schema: Value,
        source: SchemaSource,
        confidence: f32,
    ) {
        let discovered = DiscoveredSchema {
            schema,
            source,
            confidence,
            url_pattern: Some(url_pattern.clone()),
        };
        self.cache.write().insert(url_pattern, discovered);
    }

    /// Detect schema evolution between a known schema and a newly inferred one.
    ///
    /// Returns a diff describing added/removed/changed fields.
    ///
    /// # Example
    ///
    /// ```
    /// use stygian_graph::application::schema_discovery::{SchemaDiscoveryService, SchemaDiscoveryConfig};
    /// use serde_json::json;
    ///
    /// let svc = SchemaDiscoveryService::new(SchemaDiscoveryConfig::default(), None);
    ///
    /// let old = json!({
    ///     "type": "object",
    ///     "properties": {"name": {"type": "string"}, "price": {"type": "number"}}
    /// });
    /// let new = json!({
    ///     "type": "object",
    ///     "properties": {"name": {"type": "string"}, "discount": {"type": "number"}}
    /// });
    ///
    /// let diff = svc.detect_evolution(&old, &new);
    /// assert!(diff.added_fields.contains(&"discount".to_string()));
    /// assert!(diff.removed_fields.contains(&"price".to_string()));
    /// ```
    pub fn detect_evolution(&self, old_schema: &Value, new_schema: &Value) -> SchemaDiff {
        let old_props = old_schema
            .get("properties")
            .and_then(Value::as_object)
            .cloned()
            .unwrap_or_default();
        let new_props = new_schema
            .get("properties")
            .and_then(Value::as_object)
            .cloned()
            .unwrap_or_default();

        let added_fields: Vec<String> = new_props
            .keys()
            .filter(|k| !old_props.contains_key(*k))
            .cloned()
            .collect();

        let removed_fields: Vec<String> = old_props
            .keys()
            .filter(|k| !new_props.contains_key(*k))
            .cloned()
            .collect();

        let type_changes: Vec<(String, String, String)> = old_props
            .iter()
            .filter_map(|(k, old_v)| {
                let new_v = new_props.get(k)?;
                let old_t = old_v.get("type").and_then(Value::as_str).unwrap_or("any");
                let new_t = new_v.get("type").and_then(Value::as_str).unwrap_or("any");
                (old_t != new_t).then(|| (k.clone(), old_t.to_string(), new_t.to_string()))
            })
            .collect();

        let is_compatible = removed_fields.is_empty() && type_changes.is_empty();

        SchemaDiff {
            added_fields,
            removed_fields,
            type_changes,
            is_compatible,
        }
    }

    /// Discover a JSON Schema by introspecting a live GraphQL endpoint.
    ///
    /// Fires the standard `__schema` introspection query, converts the returned
    /// SDL types to a JSON Schema representation, and caches the result by
    /// endpoint URL.
    ///
    /// # Errors
    ///
    /// Returns `Err` if no GraphQL service is configured, if the endpoint is
    /// unreachable, if the response contains GraphQL errors, or if the
    /// introspection response cannot be parsed.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use stygian_graph::application::schema_discovery::{SchemaDiscoveryService, SchemaDiscoveryConfig};
    /// use stygian_graph::adapters::graphql::GraphQlService;
    /// use std::sync::Arc;
    ///
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// let gql = Arc::new(GraphQlService::new(Default::default(), None));
    /// let svc = SchemaDiscoveryService::new(SchemaDiscoveryConfig::default(), None)
    ///     .with_graphql_service(gql);
    /// let schema = svc.infer_from_graphql("https://api.example.com/graphql", None).await;
    /// # });
    /// ```
    #[allow(clippy::indexing_slicing)]
    pub async fn infer_from_graphql(
        &self,
        endpoint: &str,
        auth: Option<GraphQlAuth>,
    ) -> Result<DiscoveredSchema> {
        // ── 1. Cache check ────────────────────────────────────────────────
        if self.config.cache_schemas {
            let cache = self.cache.read();
            if let Some(cached) = cache.get(endpoint) {
                debug!(endpoint, "GraphQL introspection cache hit");
                return Ok(DiscoveredSchema {
                    source: SchemaSource::Cached,
                    ..cached.clone()
                });
            }
        }

        // ── 2. Require a GraphQL service ──────────────────────────────────
        let service = self.graphql_service.as_ref().ok_or_else(|| {
            StygianError::Service(ServiceError::Unavailable(
                "No GraphQL service configured for introspection".to_string(),
            ))
        })?;

        // ── 3. Build ServiceInput with introspection query ────────────────
        let mut params = json!({
            "query": INTROSPECTION_QUERY,
        });
        if let Some(a) = auth {
            params["auth"] = json!({
                "kind": match a.kind {
                    crate::ports::GraphQlAuthKind::Bearer => "bearer",
                    crate::ports::GraphQlAuthKind::ApiKey => "api_key",
                    crate::ports::GraphQlAuthKind::Header => "header",
                    crate::ports::GraphQlAuthKind::None => "none",
                },
                "token": a.token,
            });
            if let Some(header) = a.header_name {
                params["auth"]["header_name"] = json!(header);
            }
        }

        let input = ServiceInput {
            url: endpoint.to_string(),
            params,
        };

        // ── 4. Execute ────────────────────────────────────────────────────
        let output = service.execute(input).await?;

        // ── 5. Parse __schema ─────────────────────────────────────────────
        let response_json: Value = serde_json::from_str(&output.data)
            .map_err(|e| StygianError::Service(ServiceError::InvalidResponse(e.to_string())))?;
        let introspection = response_json.get("__schema").ok_or_else(|| {
            StygianError::Service(ServiceError::InvalidResponse(
                "introspection response missing __schema key".to_string(),
            ))
        })?;

        // ── 6. Build JSON Schema from types ───────────────────────────────
        let query_type_name = introspection
            .get("queryType")
            .and_then(|qt| qt.get("name"))
            .and_then(Value::as_str)
            .unwrap_or("Query")
            .to_string();

        let types = introspection
            .get("types")
            .and_then(Value::as_array)
            .cloned()
            .unwrap_or_default();

        let mut definitions = Map::new();
        for gql_type in &types {
            let name = gql_type.get("name").and_then(Value::as_str).unwrap_or("");
            // Skip built-in introspection types
            if name.is_empty() || name.starts_with('_') {
                continue;
            }
            let def = Self::convert_type_to_definition(gql_type);
            definitions.insert(name.to_string(), def);
        }

        let schema = json!({
            "type": "object",
            "description": format!("GraphQL schema for {endpoint}"),
            "definitions": Value::Object(definitions),
            "queryType": query_type_name,
        });

        let discovered = DiscoveredSchema {
            schema,
            source: SchemaSource::AiInference,
            confidence: 1.0,
            url_pattern: Some(endpoint.to_string()),
        };

        // ── 7. Cache ───────────────────────────────────────────────────────
        if self.config.cache_schemas {
            self.cache
                .write()
                .insert(endpoint.to_string(), discovered.clone());
        }

        Ok(discovered)
    }

    /// Convert a top-level GraphQL type definition to a JSON Schema object.
    #[allow(clippy::indexing_slicing)]
    fn convert_type_to_definition(gql_type: &Value) -> Value {
        let kind = gql_type.get("kind").and_then(Value::as_str).unwrap_or("");
        match kind {
            "OBJECT" | "INTERFACE" | "INPUT_OBJECT" => {
                let fields: Vec<Value> = gql_type
                    .get("fields")
                    .or_else(|| gql_type.get("inputFields"))
                    .and_then(Value::as_array)
                    .cloned()
                    .unwrap_or_default();

                let mut properties = Map::new();
                let mut required: Vec<Value> = Vec::new();

                for field in &fields {
                    let field_name = field.get("name").and_then(Value::as_str).unwrap_or("");
                    if field_name.is_empty() {
                        continue;
                    }
                    let type_ref = &field["type"];
                    // NON_NULL at the outermost level means the field is required
                    if type_ref.get("kind").and_then(Value::as_str) == Some("NON_NULL") {
                        required.push(json!(field_name));
                    }
                    properties.insert(field_name.to_string(), Self::convert_type_ref(type_ref));
                }

                let mut obj = json!({
                    "type": "object",
                    "properties": Value::Object(properties),
                });
                if !required.is_empty() {
                    obj["required"] = json!(required);
                }
                obj
            }
            "ENUM" => {
                let values: Vec<Value> = gql_type
                    .get("enumValues")
                    .and_then(Value::as_array)
                    .map(|vals| {
                        vals.iter()
                            .filter_map(|v| v.get("name").and_then(Value::as_str))
                            .map(|s| json!(s))
                            .collect()
                    })
                    .unwrap_or_default();
                json!({ "type": "string", "enum": values })
            }
            "SCALAR" => {
                let name = gql_type.get("name").and_then(Value::as_str).unwrap_or("");
                Self::scalar_to_json_schema(name)
            }
            _ => json!({}),
        }
    }

    /// Recursively convert a GraphQL type reference (field type) to JSON Schema.
    fn convert_type_ref(type_ref: &Value) -> Value {
        let kind = type_ref.get("kind").and_then(Value::as_str).unwrap_or("");
        match kind {
            "NON_NULL" => Self::convert_type_ref(&type_ref["ofType"]),
            "LIST" => json!({
                "type": "array",
                "items": Self::convert_type_ref(&type_ref["ofType"]),
            }),
            "OBJECT" | "INTERFACE" | "INPUT_OBJECT" | "ENUM" => {
                let name = type_ref.get("name").and_then(Value::as_str).unwrap_or("");
                json!({ "$ref": format!("#/definitions/{name}") })
            }
            "SCALAR" => {
                let name = type_ref.get("name").and_then(Value::as_str).unwrap_or("");
                Self::scalar_to_json_schema(name)
            }
            _ => json!({}),
        }
    }

    /// Map a GraphQL scalar name to its JSON Schema type.
    fn scalar_to_json_schema(name: &str) -> Value {
        match name {
            "String" | "ID" => json!({ "type": "string" }),
            "Int" => json!({ "type": "integer" }),
            "Float" => json!({ "type": "number" }),
            "Boolean" => json!({ "type": "boolean" }),
            s if s.to_ascii_lowercase().contains("datetime")
                || s.to_ascii_lowercase().contains("date") =>
            {
                json!({ "type": "string", "format": "date-time" })
            }
            _ => json!({}),
        }
    }

    /// Validate that a value is a structurally valid JSON Schema object.
    ///
    /// Checks for the presence of a `type` or `properties` field.
    ///
    /// # Example
    ///
    /// ```
    /// use stygian_graph::application::schema_discovery::SchemaDiscoveryService;
    /// use serde_json::json;
    ///
    /// assert!(SchemaDiscoveryService::is_valid_schema(&json!({"type": "object"})));
    /// assert!(!SchemaDiscoveryService::is_valid_schema(&json!("not a schema")));
    /// ```
    pub fn is_valid_schema(schema: &Value) -> bool {
        if !schema.is_object() {
            return false;
        }
        schema.get("type").is_some() || schema.get("properties").is_some()
    }
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::indexing_slicing,
    clippy::approx_constant,
    clippy::significant_drop_tightening,
    clippy::float_cmp,
    clippy::unnecessary_map_or
)]
mod tests {
    use super::*;
    use serde_json::json;

    fn svc() -> SchemaDiscoveryService {
        SchemaDiscoveryService::new(SchemaDiscoveryConfig::default(), None)
    }

    // --- infer_from_example ---

    #[test]
    fn test_infer_object_schema() {
        let s = svc();
        let schema = s.infer_from_example(&json!({"name": "Alice", "age": 30, "active": true}));
        assert_eq!(schema["type"].as_str().unwrap(), "object");
        assert_eq!(
            schema["properties"]["name"]["type"].as_str().unwrap(),
            "string"
        );
        assert_eq!(
            schema["properties"]["age"]["type"].as_str().unwrap(),
            "integer"
        );
        assert_eq!(
            schema["properties"]["active"]["type"].as_str().unwrap(),
            "boolean"
        );
    }

    #[test]
    fn test_infer_array_schema() {
        let s = svc();
        let schema = s.infer_from_example(&json!([{"id": 1}, {"id": 2}]));
        assert_eq!(schema["type"].as_str().unwrap(), "array");
        assert_eq!(schema["items"]["type"].as_str().unwrap(), "object");
    }

    #[test]
    fn test_infer_string_schema() {
        let s = svc();
        let schema = s.infer_from_example(&json!("hello"));
        assert_eq!(schema["type"].as_str().unwrap(), "string");
    }

    #[test]
    fn test_infer_number_float() {
        let s = svc();
        let schema = s.infer_from_example(&json!(3.14));
        assert_eq!(schema["type"].as_str().unwrap(), "number");
    }

    #[test]
    fn test_infer_null() {
        let s = svc();
        let schema = s.infer_from_example(&Value::Null);
        assert_eq!(schema["type"].as_str().unwrap(), "null");
    }

    // --- is_valid_schema ---

    #[test]
    fn test_valid_schema_with_type() {
        assert!(SchemaDiscoveryService::is_valid_schema(
            &json!({"type": "object"})
        ));
    }

    #[test]
    fn test_valid_schema_with_properties() {
        assert!(SchemaDiscoveryService::is_valid_schema(
            &json!({"properties": {"x": {"type": "string"}}})
        ));
    }

    #[test]
    fn test_invalid_schema_string() {
        assert!(!SchemaDiscoveryService::is_valid_schema(&json!(
            "not schema"
        )));
    }

    #[test]
    fn test_invalid_schema_empty_object() {
        // An empty object has neither "type" nor "properties"
        assert!(!SchemaDiscoveryService::is_valid_schema(&json!({})));
    }

    // --- detect_evolution ---

    #[test]
    fn test_evolution_added_field() {
        let s = svc();
        let old = json!({"type": "object", "properties": {"name": {"type": "string"}}});
        let new = json!({"type": "object", "properties": {"name": {"type": "string"}, "email": {"type": "string"}}});
        let diff = s.detect_evolution(&old, &new);
        assert!(diff.added_fields.contains(&"email".to_string()));
        assert!(diff.removed_fields.is_empty());
        assert!(diff.is_compatible);
    }

    #[test]
    fn test_evolution_removed_field() {
        let s = svc();
        let old = json!({"type": "object", "properties": {"name": {"type": "string"}, "age": {"type": "integer"}}});
        let new = json!({"type": "object", "properties": {"name": {"type": "string"}}});
        let diff = s.detect_evolution(&old, &new);
        assert!(diff.removed_fields.contains(&"age".to_string()));
        assert!(!diff.is_compatible);
    }

    #[test]
    fn test_evolution_type_change() {
        let s = svc();
        let old = json!({"type": "object", "properties": {"id": {"type": "string"}}});
        let new = json!({"type": "object", "properties": {"id": {"type": "integer"}}});
        let diff = s.detect_evolution(&old, &new);
        assert_eq!(diff.type_changes.len(), 1);
        assert_eq!(
            diff.type_changes[0],
            (
                "id".to_string(),
                "string".to_string(),
                "integer".to_string()
            )
        );
        assert!(!diff.is_compatible);
    }

    #[test]
    fn test_evolution_no_change() {
        let s = svc();
        let schema = json!({"type": "object", "properties": {"x": {"type": "string"}}});
        let diff = s.detect_evolution(&schema, &schema);
        assert!(diff.added_fields.is_empty());
        assert!(diff.removed_fields.is_empty());
        assert!(diff.is_compatible);
    }

    // --- corrections ---

    #[test]
    fn test_correction_overrides_inferred_type() {
        let s = svc();
        s.add_correction("id".to_string(), json!({"type": "integer"}));

        let schema = json!({
            "type": "object",
            "properties": {
                "id": {"type": "string"},
                "name": {"type": "string"}
            }
        });
        let corrected = s.apply_corrections(schema);
        assert_eq!(
            corrected["properties"]["id"]["type"].as_str().unwrap(),
            "integer"
        );
        assert_eq!(
            corrected["properties"]["name"]["type"].as_str().unwrap(),
            "string"
        );
    }

    // --- cache ---

    #[test]
    fn test_cache_and_retrieve() {
        let s = svc();
        let schema = json!({"type": "object", "properties": {"title": {"type": "string"}}});
        s.cache_schema(
            "example.com".to_string(),
            schema.clone(),
            SchemaSource::UserCorrection,
            1.0,
        );

        let cache = s.cache.read();
        let entry = cache.get("example.com").unwrap();
        assert_eq!(entry.schema, schema);
        assert_eq!(entry.source, SchemaSource::UserCorrection);
    }

    // --- HTML inference without provider ---

    #[tokio::test]
    async fn test_infer_from_html_no_provider() {
        let s = svc();
        let result = s
            .infer_from_html("<html><body>test</body></html>", None)
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("No AI provider"));
    }

    // --- HTML inference with cache hit ---

    #[tokio::test]
    async fn test_infer_from_html_cache_hit() {
        let s = svc();
        let schema = json!({"type": "object"});
        s.cache_schema(
            "example.com".to_string(),
            schema.clone(),
            SchemaSource::Cached,
            0.9,
        );

        let result = s
            .infer_from_html("<html/>", Some("example.com"))
            .await
            .unwrap();
        assert_eq!(result.source, SchemaSource::Cached);
        assert_eq!(result.schema, schema);
    }

    // ── GraphQL introspection tests ──────────────────────────────────────────

    /// Minimal mock [`ScrapingService`] that returns a pre-baked `Value` as `data`.
    struct MockGraphQlService(Value);

    #[async_trait::async_trait]
    impl ScrapingService for MockGraphQlService {
        fn name(&self) -> &'static str {
            "mock_graphql"
        }
        async fn execute(
            &self,
            _input: crate::ports::ServiceInput,
        ) -> Result<crate::ports::ServiceOutput> {
            Ok(crate::ports::ServiceOutput {
                data: serde_json::to_string(&self.0).unwrap_or_default(),
                metadata: Value::default(),
            })
        }
    }

    impl SchemaDiscoveryService {
        /// Test-only constructor: pre-bake a GraphQL introspection response.
        ///
        /// The `response` value should represent the `data` object that a real
        /// GraphQL service would return (i.e. `{ "__schema": { ... } }`).
        fn with_mock_graphql(config: SchemaDiscoveryConfig, response: Value) -> Self {
            let svc = Arc::new(MockGraphQlService(response));
            Self::new(config, None).with_graphql_service(svc)
        }
    }

    fn make_introspection_response_simple() -> Value {
        json!({
            "__schema": {
                "queryType": { "name": "Query" },
                "mutationType": null,
                "subscriptionType": null,
                "types": [
                    {
                        "kind": "OBJECT",
                        "name": "Query",
                        "fields": [
                            {
                                "name": "user",
                                "type": { "kind": "OBJECT", "name": "User", "ofType": null }
                            }
                        ],
                        "inputFields": null,
                        "interfaces": [],
                        "enumValues": null,
                        "possibleTypes": null
                    },
                    {
                        "kind": "OBJECT",
                        "name": "User",
                        "fields": [
                            {
                                "name": "id",
                                "type": { "kind": "NON_NULL", "name": null, "ofType": { "kind": "SCALAR", "name": "ID", "ofType": null } }
                            },
                            {
                                "name": "name",
                                "type": { "kind": "SCALAR", "name": "String", "ofType": null }
                            }
                        ],
                        "inputFields": null,
                        "interfaces": [],
                        "enumValues": null,
                        "possibleTypes": null
                    },
                    {
                        "kind": "SCALAR",
                        "name": "String",
                        "fields": null,
                        "inputFields": null,
                        "interfaces": null,
                        "enumValues": null,
                        "possibleTypes": null
                    },
                    {
                        "kind": "SCALAR",
                        "name": "ID",
                        "fields": null,
                        "inputFields": null,
                        "interfaces": null,
                        "enumValues": null,
                        "possibleTypes": null
                    }
                ],
                "directives": []
            }
        })
    }

    #[tokio::test]
    async fn introspection_no_graphql_service() {
        let s = svc(); // no graphql_service configured
        let result = s
            .infer_from_graphql("https://api.example.com/graphql", None)
            .await;
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("No GraphQL service")
        );
    }

    #[test]
    fn graphql_type_to_json_schema_scalar() {
        assert_eq!(
            SchemaDiscoveryService::scalar_to_json_schema("String"),
            json!({"type": "string"})
        );
        assert_eq!(
            SchemaDiscoveryService::scalar_to_json_schema("Int"),
            json!({"type": "integer"})
        );
        assert_eq!(
            SchemaDiscoveryService::scalar_to_json_schema("Float"),
            json!({"type": "number"})
        );
        assert_eq!(
            SchemaDiscoveryService::scalar_to_json_schema("Boolean"),
            json!({"type": "boolean"})
        );
        assert_eq!(
            SchemaDiscoveryService::scalar_to_json_schema("ID"),
            json!({"type": "string"})
        );
        assert_eq!(
            SchemaDiscoveryService::scalar_to_json_schema("DateTime"),
            json!({"type": "string", "format": "date-time"})
        );
        // Unknown scalar → permissive empty schema
        assert_eq!(
            SchemaDiscoveryService::scalar_to_json_schema("JSON"),
            json!({})
        );
    }

    #[test]
    fn graphql_type_to_json_schema_object() {
        let gql_type = json!({
            "kind": "OBJECT",
            "name": "User",
            "fields": [
                {
                    "name": "id",
                    "type": { "kind": "SCALAR", "name": "ID", "ofType": null }
                },
                {
                    "name": "email",
                    "type": { "kind": "SCALAR", "name": "String", "ofType": null }
                }
            ]
        });
        let schema = SchemaDiscoveryService::convert_type_to_definition(&gql_type);
        assert_eq!(schema["type"].as_str().unwrap(), "object");
        assert_eq!(
            schema["properties"]["id"]["type"].as_str().unwrap(),
            "string"
        );
        assert_eq!(
            schema["properties"]["email"]["type"].as_str().unwrap(),
            "string"
        );
        // Neither field is NON_NULL, so no required array
        assert!(
            schema.get("required").is_none()
                || schema["required"].as_array().is_none_or(Vec::is_empty)
        );
    }

    #[test]
    fn graphql_non_null_adds_to_required() {
        let gql_type = json!({
            "kind": "OBJECT",
            "name": "Product",
            "fields": [
                {
                    "name": "sku",
                    "type": {
                        "kind": "NON_NULL",
                        "name": null,
                        "ofType": { "kind": "SCALAR", "name": "String", "ofType": null }
                    }
                },
                {
                    "name": "description",
                    "type": { "kind": "SCALAR", "name": "String", "ofType": null }
                }
            ]
        });
        let schema = SchemaDiscoveryService::convert_type_to_definition(&gql_type);
        let required = schema["required"].as_array().unwrap();
        assert!(required.contains(&json!("sku")));
        assert!(!required.contains(&json!("description")));
    }

    #[tokio::test]
    async fn introspection_result_cached() {
        let response = make_introspection_response_simple();
        let s =
            SchemaDiscoveryService::with_mock_graphql(SchemaDiscoveryConfig::default(), response);

        // First call — fetches from mock service
        let first = s
            .infer_from_graphql("https://api.example.com/graphql", None)
            .await
            .unwrap();
        assert_eq!(first.source, SchemaSource::AiInference);
        assert_eq!(first.confidence, 1.0);

        // Second call — served from cache (source changes to Cached)
        let second = s
            .infer_from_graphql("https://api.example.com/graphql", None)
            .await
            .unwrap();
        assert_eq!(second.source, SchemaSource::Cached);
        assert_eq!(second.schema["queryType"].as_str().unwrap(), "Query");
    }
}