elusion 8.2.0

Elusion is a modern DataFrame / Data Engineering / Data Analysis library that combines the familiarity of DataFrame operations (like those in PySpark, Pandas, and Polars) with the power of SQL query building. It provides flexible query construction without enforcing strict operation ordering, enabling developers to write intuitive and maintainable data transformations.
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
#[cfg(feature = "fabric")]
use crate::prelude::*;
#[cfg(feature = "fabric")]
use crate::ElusionError;
#[cfg(feature = "fabric")]
use crate::ElusionResult;
#[cfg(feature = "fabric")]
use crate::CustomDataFrame;
#[cfg(feature = "fabric")]
use reqwest;
#[cfg(feature = "fabric")]
use datafusion::arrow::record_batch::RecordBatch;
#[cfg(feature = "fabric")]
use datafusion::parquet::arrow::ArrowWriter;
#[cfg(feature = "fabric")]
use datafusion::parquet::file::properties::{WriterProperties, WriterVersion};
#[cfg(feature = "fabric")]
use datafusion::parquet::basic::Compression;
#[cfg(feature = "fabric")]
use azure_identity::{ClientSecretCredential, ClientSecretCredentialOptions};
#[cfg(feature = "fabric")]
use azure_core::credentials::TokenCredential;

#[cfg(feature = "fabric")]
#[derive(Debug, Clone)]
pub enum FabricAuthMethod {
    AzureCLI,
    ServicePrincipal {
        tenant_id: String,
        client_id: String,
        client_secret: String,
    },
}

#[cfg(feature = "fabric")]
#[derive(Debug, Clone)]
pub struct ParsedOneLakePath {
    pub workspace_id: String,
    pub lakehouse_id: Option<String>,
    pub warehouse_id: Option<String>,
    pub base_path: String,
    pub is_lakehouse: bool,
}

#[cfg(feature = "fabric")]
#[derive(Debug, Clone)]
pub struct OneLakeConfig {
    pub workspace_id: String,
    pub lakehouse_id: Option<String>,
    pub warehouse_id: Option<String>,
    pub auth_method: FabricAuthMethod,
}

#[cfg(feature = "fabric")]
pub struct OneLakeClient {
    config: OneLakeConfig,
    access_token: Option<String>,
    fabric_token: Option<String>,
}

#[cfg(feature = "fabric")]
impl OneLakeConfig {
    pub fn new(
        workspace_id: String,
        lakehouse_id: Option<String>,
        warehouse_id: Option<String>,
    ) -> Self {
        Self {
            workspace_id,
            lakehouse_id,
            warehouse_id,
            auth_method: FabricAuthMethod::AzureCLI,
        }
    }

    pub fn new_with_service_principal(
        tenant_id: String,
        client_id: String,
        client_secret: String,
        workspace_id: String,
        lakehouse_id: Option<String>,
        warehouse_id: Option<String>,
    ) -> Self {
        Self {
            workspace_id,
            lakehouse_id,
            warehouse_id,
            auth_method: FabricAuthMethod::ServicePrincipal {
                tenant_id,
                client_id,
                client_secret,
            },
        }
    }
}

#[cfg(feature = "fabric")]
impl OneLakeClient {
    pub fn new(config: OneLakeConfig) -> Self {
        Self {
            config,
            access_token: None,
            fabric_token: None,
        }
    }

    pub async fn authenticate(&mut self) -> ElusionResult<()> {
        match &self.config.auth_method {
            FabricAuthMethod::AzureCLI => {
                self.authenticate_with_azure_cli().await
            },
            FabricAuthMethod::ServicePrincipal { tenant_id, client_id, client_secret } => {
                self.authenticate_with_service_principal(
                    tenant_id.clone(),
                    client_id.clone(),
                    client_secret.clone(),
                ).await
            }
        }
    }

    /// Authenticate using service principal credentials for Fabric/OneLake
    async fn authenticate_with_service_principal(
        &mut self,
        tenant_id: String,
        client_id: String,
        client_secret: String,
    ) -> ElusionResult<()> {
        println!("🔐 Authenticating with Service Principal for Fabric/OneLake...");
        
        let options = ClientSecretCredentialOptions::default();
        
        let credential = ClientSecretCredential::new(
            tenant_id.as_str().into(),
            client_id.into(),
            client_secret.into(),
            Some(options),
        ).map_err(|e| ElusionError::Custom(format!("Failed to create credential: {}", e)))?;
        
        // Get Azure Storage token for OneLake access
        let storage_scopes = &["https://storage.azure.com/.default"];
        match credential.get_token(storage_scopes, None).await {
            Ok(token_response) => {
                self.access_token = Some(token_response.token.secret().to_string());
                println!("✅ Successfully obtained Azure Storage token");
            },
            Err(e) => {
                return Err(ElusionError::Custom(format!(
                    "Failed to get Azure Storage token: {}. \
                    Please verify your tenant_id, client_id, and client_secret are correct, \
                    and that the service principal has appropriate permissions.",
                    e
                )));
            }
        }

        // Get Fabric API token for workspace/lakehouse operations
        let fabric_scopes = &["https://api.fabric.microsoft.com/.default"];
        match credential.get_token(fabric_scopes, None).await {
            Ok(token_response) => {
                self.fabric_token = Some(token_response.token.secret().to_string());
                println!("✅ Successfully obtained Fabric API token");
            },
            Err(e) => {
                println!("⚠️ Warning: Failed to get Fabric API token: {}. Some operations may be limited.", e);
                // Don't fail here as storage token is sufficient for basic file operations
            }
        }

        println!("✅ Successfully authenticated with Service Principal for Fabric/OneLake");
        Ok(())
    }

    pub async fn authenticate_with_azure_cli(&mut self) -> ElusionResult<()> {
        println!("🔍 Authenticating with Azure CLI for Fabric - OneLake access...");
        
        match self.execute_az_via_python(&["--version"]).await {
            Ok(version_output) => {
                if version_output.status.success() {
                    println!("✅ Azure CLI via Python works");
                    
                    // Check if logged in and get tokens
                    if self.get_tokens_via_python().await.is_ok() {
                        println!("✅ Successfully authenticated with Fabric - OneLake!");
                        return Ok(());
                    }
                }
            },
            Err(_) => {}
        }

        let az_paths = self.get_azure_cli_paths();
        
        for az_path in az_paths.iter() {
            if let Ok(output) = std::process::Command::new(az_path)
                .args(["--version"])
                .env("PYTHONIOENCODING", "utf-8")
                .env("PYTHONUTF8", "1")
                .output() 
            {
                if output.status.success() && self.get_tokens_via_cli(az_path).await.is_ok() {
                    println!("✅ Successfully authenticated with Fabric - OneLake!");
                    return Ok(());
                }
            }
        }

        Err(ElusionError::Custom(
            "Fabric - OneLake authentication failed. Please run 'az login' and ensure you have access to Microsoft Fabric.".to_string()
        ))
    }

    async fn get_tokens_via_python(&mut self) -> ElusionResult<()> {
        // Check if logged in
        match self.execute_az_via_python(&["account", "show"]).await {
            Ok(account_output) => {
                if account_output.status.success() {
                    //  Azure Storage token 
                    if let Ok(token_output) = self.execute_az_via_python(&["account", "get-access-token", "--resource", "https://storage.azure.com/", "--output", "json"]).await {
                        if token_output.status.success() {
                            let token_json = String::from_utf8_lossy(&token_output.stdout);
                            if let Ok(token_data) = serde_json::from_str::<serde_json::Value>(&token_json) {
                                if let Some(access_token) = token_data["accessToken"].as_str() {
                                    self.access_token = Some(access_token.to_string());
                                }
                            }
                        }
                    }

                    // Get Fabric API token (for workspace/lakehouse discovery if needed)
                    if let Ok(fabric_output) = self.execute_az_via_python(&["account", "get-access-token", "--resource", "https://api.fabric.microsoft.com/", "--output", "json"]).await {
                        if fabric_output.status.success() {
                            let fabric_json = String::from_utf8_lossy(&fabric_output.stdout);
                            if let Ok(fabric_data) = serde_json::from_str::<serde_json::Value>(&fabric_json) {
                                if let Some(fabric_token) = fabric_data["accessToken"].as_str() {
                                    self.fabric_token = Some(fabric_token.to_string());
                                }
                            }
                        }
                    }

                    if self.access_token.is_some() {
                        return Ok(());
                    }
                }
            },
            Err(_) => {}
        }
        Err(ElusionError::Custom("Failed to get tokens via Python".to_string()))
    }

    async fn get_tokens_via_cli(&mut self, az_path: &str) -> ElusionResult<()> {
        // Check login and get tokens
        if let Ok(account_output) = std::process::Command::new(az_path)
            .args(["account", "show"])
            .env("PYTHONIOENCODING", "utf-8")
            .env("PYTHONUTF8", "1")
            .output() 
        {
            if account_output.status.success() {
                //  Azure Storage token
                if let Ok(storage_token_output) = std::process::Command::new(az_path)
                    .args(["account", "get-access-token", "--resource", "https://storage.azure.com/", "--output", "json"])
                    .env("PYTHONIOENCODING", "utf-8")
                    .env("PYTHONUTF8", "1")
                    .output()
                {
                    if storage_token_output.status.success() {
                        let token_json = String::from_utf8_lossy(&storage_token_output.stdout);
                        if let Ok(token_data) = serde_json::from_str::<serde_json::Value>(&token_json) {
                            if let Some(access_token) = token_data["accessToken"].as_str() {
                                self.access_token = Some(access_token.to_string());
                            }
                        }
                    }
                }

                //  Fabric token 
                if let Ok(fabric_token_output) = std::process::Command::new(az_path)
                    .args(["account", "get-access-token", "--resource", "https://api.fabric.microsoft.com/", "--output", "json"])
                    .env("PYTHONIOENCODING", "utf-8")
                    .env("PYTHONUTF8", "1")
                    .output()
                {
                    if fabric_token_output.status.success() {
                        let fabric_json = String::from_utf8_lossy(&fabric_token_output.stdout);
                        if let Ok(fabric_data) = serde_json::from_str::<serde_json::Value>(&fabric_json) {
                            if let Some(fabric_token) = fabric_data["accessToken"].as_str() {
                                self.fabric_token = Some(fabric_token.to_string());
                            }
                        }
                    }
                }

                if self.access_token.is_some() {
                    return Ok(());
                }
            }
        }
        Err(ElusionError::Custom("Failed to get tokens via CLI".to_string()))
    }

    async fn execute_az_via_python(&self, args: &[&str]) -> ElusionResult<std::process::Output> {
        let python_path = if cfg!(target_os = "windows") {
            r#"C:\Program Files\Microsoft SDKs\Azure\CLI2\python.exe"#
        } else {
            "python3"
        };
        
        if !std::path::Path::new(python_path).exists() {
            return Err(ElusionError::Custom("Azure CLI Python not found".to_string()));
        }
        
        let mut full_args = vec!["-X", "utf8", "-m", "azure.cli"];
        full_args.extend(args);
        
        std::process::Command::new(python_path)
            .args(&full_args)
            .env("PYTHONIOENCODING", "utf-8")
            .env("PYTHONUTF8", "1")
            .output()
            .map_err(|e| ElusionError::Custom(format!("Failed to execute Azure CLI via Python: {}", e)))
    }

    fn get_azure_cli_paths(&self) -> Vec<&'static str> {
        if cfg!(target_os = "windows") {
            vec![
                r#"C:\Program Files\Microsoft SDKs\Azure\CLI2\python.exe"#,
                "az.cmd",
                "az.exe",
                "C:\\Program Files\\Microsoft SDKs\\Azure\\CLI2\\wbin\\az.cmd",
                "C:\\Program Files (x86)\\Microsoft SDKs\\Azure\\CLI2\\wbin\\az.cmd",
            ]
        } else if cfg!(target_os = "macos") {
            vec![
                "az",
                "/usr/local/bin/az",
                "/opt/homebrew/bin/az",
            ]
        } else {
            vec![
                "az",
                "/usr/local/bin/az",
                "/usr/bin/az",
                "/home/$USER/.local/bin/az",
            ]
        }
    }

    fn build_onelake_read_url(&self, file_path: &str) -> ElusionResult<String> {
        let clean_path = file_path.trim_start_matches('/');
        
        if let Some(lakehouse_id) = &self.config.lakehouse_id {
            Ok(format!(
                "https://onelake.dfs.fabric.microsoft.com/{}/{}/Files/{}", 
                self.config.workspace_id,
                lakehouse_id,
                clean_path
            ))
        } else if let Some(warehouse_id) = &self.config.warehouse_id {
            Ok(format!(
                "https://onelake.dfs.fabric.microsoft.com/{}/{}/Files/{}", 
                self.config.workspace_id,
                warehouse_id,
                clean_path
            ))
        } else {
            Err(ElusionError::Custom("Either lakehouse_id or warehouse_id must be specified".to_string()))
        }
    }

    fn build_onelake_write_url(&self, file_path: &str) -> ElusionResult<String> {
        let clean_path = file_path.trim_start_matches('/');
        
        if let Some(lakehouse_id) = &self.config.lakehouse_id {
            let is_guid = lakehouse_id.len() == 36 && 
                         lakehouse_id.chars().filter(|&c| c == '-').count() == 4;
            
            if is_guid {

                Ok(format!(
                    "https://onelake.dfs.fabric.microsoft.com/{}/{}/Files/{}", 
                    self.config.workspace_id,
                    lakehouse_id,
                    clean_path
                ))
            } else {
                Ok(format!(
                    "https://onelake.dfs.fabric.microsoft.com/{}/{}.Lakehouse/Files/{}", 
                    self.config.workspace_id,
                    lakehouse_id,
                    clean_path
                ))
            }
        } else if let Some(warehouse_id) = &self.config.warehouse_id {
            let is_guid = warehouse_id.len() == 36 && 
                         warehouse_id.chars().filter(|&c| c == '-').count() == 4;
            
            if is_guid {
                Ok(format!(
                    "https://onelake.dfs.fabric.microsoft.com/{}/{}/Files/{}", 
                    self.config.workspace_id,
                    warehouse_id,
                    clean_path
                ))
            } else {
                Ok(format!(
                    "https://onelake.dfs.fabric.microsoft.com/{}/{}.Warehouse/Files/{}", 
                    self.config.workspace_id,
                    warehouse_id,
                    clean_path
                ))
            }
        } else {
            Err(ElusionError::Custom("Either lakehouse_id or warehouse_id must be specified".to_string()))
        }
    }

    // Download file from OneLake
    pub async fn download_file(&mut self, file_path: &str) -> ElusionResult<Vec<u8>> {
        self.authenticate().await?;
        let token = self.access_token.as_ref()
            .ok_or_else(|| ElusionError::Custom("Not authenticated".to_string()))?;

        let onelake_url = self.build_onelake_read_url(file_path)?;

        println!("📥 Downloading file from OneLake: {}", file_path);

        let response = reqwest::Client::new()
            .get(&onelake_url)
            .bearer_auth(token)
            .header("x-ms-version", "2020-06-12")
            .send()
            .await
            .map_err(|e| ElusionError::Custom(format!("Failed to download file: {}", e)))?;

        if response.status().is_success() {
            let content = response.bytes().await
                .map_err(|e| ElusionError::Custom(format!("Failed to read file content: {}", e)))?;
            
            println!("✅ Successfully downloaded {} bytes", content.len());
            Ok(content.to_vec())
        } else {
            Err(ElusionError::Custom(format!("Failed to download file '{}': HTTP {}", file_path, response.status())))
        }
    }

    // Upload file to OneLake
    pub async fn upload_file(&mut self, file_path: &str, content: Vec<u8>) -> ElusionResult<()> {
        self.authenticate().await?;
        let token = self.access_token.as_ref()
            .ok_or_else(|| ElusionError::Custom("Not authenticated".to_string()))?;

        let onelake_url = self.build_onelake_write_url(file_path)?;  // Use write URL
        
        // For ADLS Gen2, we need to use the query parameter for the resource type
        let create_url = format!("{}?resource=file", onelake_url);

        println!("📤 Uploading file to OneLake: {}", file_path);

        //  create the file
        let create_response = reqwest::Client::new()
            .put(&create_url)
            .bearer_auth(&token)
            .header("x-ms-version", "2020-06-12")
            .header("Content-Length", "0")
            .send()
            .await
            .map_err(|e| ElusionError::Custom(format!("Failed to create file: {}", e)))?;

        if !create_response.status().is_success() {
            let status = create_response.status();
            let error_text = create_response.text().await.unwrap_or_else(|_| "No error details".to_string());
            return Err(ElusionError::Custom(format!(
                "Failed to create file '{}': HTTP {} - {}", 
                file_path, 
                status, 
                error_text
            )));
        }

        // append data
        let append_url = format!("{}?action=append&position=0", onelake_url);
        
        let append_response = reqwest::Client::new()
            .patch(&append_url)
            .bearer_auth(&token)
            .header("x-ms-version", "2020-06-12")
            .header("Content-Length", content.len().to_string())
            .body(content.clone())
            .send()
            .await
            .map_err(|e| ElusionError::Custom(format!("Failed to append data: {}", e)))?;

        if !append_response.status().is_success() {
            let status = append_response.status();
            let error_text = append_response.text().await.unwrap_or_else(|_| "No error details".to_string());
            return Err(ElusionError::Custom(format!(
                "Failed to append data to '{}': HTTP {} - {}", 
                file_path, 
                status, 
                error_text
            )));
        }

        // flush the file
        let flush_url = format!("{}?action=flush&position={}", onelake_url, content.len());
        
        let flush_response = reqwest::Client::new()
            .patch(&flush_url)
            .bearer_auth(&token)
            .header("x-ms-version", "2020-06-12")
            .header("Content-Length", "0")
            .send()
            .await
            .map_err(|e| ElusionError::Custom(format!("Failed to flush file: {}", e)))?;

        if flush_response.status().is_success() {
            println!("✅ Successfully uploaded file to OneLake");
            Ok(())
        } else {
            let status = flush_response.status();
            let error_text = flush_response.text().await.unwrap_or_else(|_| "No error details".to_string());
            Err(ElusionError::Custom(format!(
                "Failed to flush file '{}': HTTP {} - {}", 
                file_path, 
                status, 
                error_text
            )))
        }
    }

    // Create client with auto-detected credentials
    pub async fn new_with_cli_auth(
        workspace_id: String,
        lakehouse_id: Option<String>,
        warehouse_id: Option<String>,
    ) -> ElusionResult<Self> {
        let config = OneLakeConfig::new(workspace_id, lakehouse_id, warehouse_id);
        Ok(OneLakeClient::new(config))
    }

    pub async fn new_with_service_principal(
        tenant_id: String,
        client_id: String,
        client_secret: String,
        workspace_id: String,
        lakehouse_id: Option<String>,
        warehouse_id: Option<String>,
    ) -> ElusionResult<Self> {
        let config = OneLakeConfig::new_with_service_principal(
            tenant_id,
            client_id,
            client_secret,
            workspace_id,
            lakehouse_id,
            warehouse_id,
        );
        Ok(OneLakeClient::new(config))
    }

    // Parse ABFSS path to extract workspace_id, lakehouse/warehouse_id, and path
    pub fn parse_abfss_path(abfss_path: &str) -> ElusionResult<ParsedOneLakePath> {
        if !abfss_path.starts_with("abfss://") {
            return Err(ElusionError::Custom(
                "Invalid ABFSS path format. Expected: abfss://workspace_id@onelake.dfs.fabric.microsoft.com/lakehouse_id/Files/...".to_string()
            ));
        }

        if !abfss_path.contains("@onelake.dfs.fabric.microsoft.com") {
            return Err(ElusionError::Custom(
                "Invalid OneLake ABFSS path. Must contain '@onelake.dfs.fabric.microsoft.com'".to_string()
            ));
        }

        let path_without_prefix = abfss_path.trim_start_matches("abfss://");
        let parts: Vec<&str> = path_without_prefix.split('@').collect();
        if parts.len() != 2 {
            return Err(ElusionError::Custom(
                "Invalid ABFSS path format. Cannot extract workspace ID".to_string()
            ));
        }

        let workspace_id = parts[0].to_string();
        let remaining_parts: Vec<&str> = parts[1].split('/').collect();
        
        if remaining_parts.len() < 3 {
            return Err(ElusionError::Custom(
                "Invalid ABFSS path format. Missing lakehouse/warehouse ID or Files path".to_string()
            ));
        }

        let lakehouse_warehouse_part = remaining_parts[1];
        let base_path = remaining_parts[2..].join("/");

        // Check if its a GUID (36 characters with hyphens)
        let is_guid = lakehouse_warehouse_part.len() == 36 && 
                     lakehouse_warehouse_part.chars().filter(|&c| c == '-').count() == 4;

        let (lakehouse_id, warehouse_id, is_lakehouse) = if lakehouse_warehouse_part.ends_with(".Lakehouse") {
            let id = lakehouse_warehouse_part.trim_end_matches(".Lakehouse").to_string();
            (Some(id), None, true)
        } else if lakehouse_warehouse_part.ends_with(".Warehouse") {
            let id = lakehouse_warehouse_part.trim_end_matches(".Warehouse").to_string();
            (None, Some(id), false)
        } else if is_guid {
            // If it's a GUID without suffix, assume it's a lakehouse
            (Some(lakehouse_warehouse_part.to_string()), None, true)
        } else {
            // Otherwise, it might be a friendly name - still assume lakehouse
            (Some(lakehouse_warehouse_part.to_string()), None, true)
        };

        Ok(ParsedOneLakePath {
            workspace_id,
            lakehouse_id,
            warehouse_id,
            base_path,
            is_lakehouse,
        })
    }
}

// ABFSS Path Implementation - Load from OneLake
#[cfg(feature = "fabric")]
pub async fn load_from_fabric_abfss_impl(
    abfss_path: &str,
    file_path: &str,
    alias: &str,
) -> ElusionResult<CustomDataFrame> {
    // Parse the ABFSS path
    let parsed = OneLakeClient::parse_abfss_path(abfss_path)?;
    
    println!("Parsed Fabric - OneLake path:");
    println!("  Workspace ID: {}", parsed.workspace_id);
    if parsed.is_lakehouse {
        println!("  Lakehouse ID: {}", parsed.lakehouse_id.as_ref().unwrap());
    } else {
        println!("  Warehouse ID: {}", parsed.warehouse_id.as_ref().unwrap());
    }
    println!("  Base Path: {}", parsed.base_path);
    println!("  File: {}", file_path);

    // Create client with auto-detected credentials
    let mut client = OneLakeClient::new_with_cli_auth(
        parsed.workspace_id,
        parsed.lakehouse_id,
        parsed.warehouse_id,
    ).await?;

    // Build full file path
    let full_file_path = if parsed.base_path == "Files" || parsed.base_path.is_empty() {
        file_path.to_string()
    } else {
        format!("{}/{}", parsed.base_path.trim_start_matches("Files/"), file_path)
    };

    // Download content from OneLake
    let content = client.download_file(&full_file_path).await?;

    // Write to temporary file
    let temp_dir = std::env::temp_dir();
    let file_extension = file_path
        .split('.')
        .last()
        .unwrap_or("tmp")
        .to_lowercase();
    
    let temp_file = temp_dir.join(format!(
        "onelake_{}_{}.{}", 
        alias,
        chrono::Utc::now().timestamp_nanos_opt().unwrap_or(0),
        file_extension
    ));
    
    std::fs::write(&temp_file, content)
        .map_err(|e| ElusionError::Custom(format!("Failed to write temporary file: {}", e)))?;

    // Use the existing load function from CustomDataFrame
    let aliased_df = CustomDataFrame::load(
        temp_file.to_str().unwrap(),
        alias
    ).await?;

    let _ = std::fs::remove_file(temp_file);

    Ok(CustomDataFrame {
        df: aliased_df.dataframe,
        table_alias: aliased_df.alias.clone(),
        from_table: aliased_df.alias.clone(),
        selected_columns: Vec::new(),
        alias_map: Vec::new(),
        aggregations: Vec::new(),
        group_by_columns: Vec::new(),
        where_conditions: Vec::new(),
        having_conditions: Vec::new(),
        order_by_columns: Vec::new(),
        limit_count: None,
        joins: Vec::new(),
        window_functions: Vec::new(),
        ctes: Vec::new(),
        subquery_source: None,
        set_operations: Vec::new(),
        query: String::new(),
        aggregated_df: None,
        union_tables: None,
        original_expressions: Vec::new(),
        needs_normalization: false,
        raw_selected_columns: Vec::new(),
        raw_group_by_columns: Vec::new(),
        raw_where_conditions: Vec::new(),
        raw_having_conditions: Vec::new(),
        raw_join_conditions: Vec::new(),
        raw_aggregations: Vec::new(),
        uses_group_by_all: false,
    })
}

// Write Parquet to OneLake using ABFSS path
#[cfg(feature = "fabric")]
pub async fn write_parquet_to_fabric_abfss_impl(
    df: &CustomDataFrame,
    abfss_path: &str,
    file_path: &str,
) -> ElusionResult<()> {
    if !file_path.ends_with(".parquet") {
        return Err(ElusionError::Custom(
            "Invalid file extension. Parquet files must end with '.parquet'".to_string()
        ));
    }

    // Parse the ABFSS path
    let parsed = OneLakeClient::parse_abfss_path(abfss_path)?;

    // Create client with auto-detected credentials
    let mut client = OneLakeClient::new_with_cli_auth(
        parsed.workspace_id,
        parsed.lakehouse_id,
        parsed.warehouse_id,
    ).await?;

    let batches: Vec<RecordBatch> = df.df.clone().collect().await
        .map_err(|e| ElusionError::Custom(format!("Failed to collect DataFrame: {}", e)))?;

    let props = WriterProperties::builder()
        .set_writer_version(WriterVersion::PARQUET_2_0)
        .set_compression(Compression::SNAPPY)
        .set_created_by("Elusion".to_string())
        .build();

    let mut buffer = Vec::new();
    {
        let schema: datafusion::arrow::datatypes::SchemaRef = df.df.schema().inner().clone();
        let mut writer = ArrowWriter::try_new(&mut buffer, schema, Some(props))
            .map_err(|e| ElusionError::Custom(format!("Failed to create Parquet writer: {}", e)))?;

        for batch in batches {
            writer.write(&batch)
                .map_err(|e| ElusionError::Custom(format!("Failed to write batch to Parquet: {}", e)))?;
        }
        writer.close()
            .map_err(|e| ElusionError::Custom(format!("Failed to close Parquet writer: {}", e)))?;
    }

    // Build full file path
    let full_file_path = if parsed.base_path == "Files" || parsed.base_path.is_empty() {
        file_path.to_string()
    } else {
        format!("{}/{}", parsed.base_path.trim_start_matches("Files/"), file_path)
    };

    client.upload_file(&full_file_path, buffer).await?;
    println!("Successfully wrote Parquet data to OneLake: {}", file_path);

    Ok(())
}

// SERVICE PRINCIPAL
// ABFSS Path Implementation - Load from OneLake with Service Principal
#[cfg(feature = "fabric")]
pub async fn load_from_fabric_abfss_with_service_principal_impl(
    tenant_id: &str,
    client_id: &str,
    client_secret: &str,
    abfss_path: &str,
    file_path: &str,
    alias: &str,
) -> ElusionResult<CustomDataFrame> {
    // Parse the ABFSS path
    let parsed = OneLakeClient::parse_abfss_path(abfss_path)?;
    
    println!("Parsed Fabric - OneLake path with Service Principal:");
    println!("  Workspace ID: {}", parsed.workspace_id);
    if parsed.is_lakehouse {
        println!("  Lakehouse ID: {}", parsed.lakehouse_id.as_ref().unwrap());
    } else {
        println!("  Warehouse ID: {}", parsed.warehouse_id.as_ref().unwrap());
    }
    println!("  Base Path: {}", parsed.base_path);
    println!("  File: {}", file_path);

    // Create client with service principal credentials
    let mut client = OneLakeClient::new_with_service_principal(
        tenant_id.to_string(),
        client_id.to_string(),
        client_secret.to_string(),
        parsed.workspace_id,
        parsed.lakehouse_id,
        parsed.warehouse_id,
    ).await?;

    // Build full file path
    let full_file_path = if parsed.base_path == "Files" || parsed.base_path.is_empty() {
        file_path.to_string()
    } else {
        format!("{}/{}", parsed.base_path.trim_start_matches("Files/"), file_path)
    };

    // Download content from OneLake
    let content = client.download_file(&full_file_path).await?;

    // Write to temporary file and load
    let temp_dir = std::env::temp_dir();
    let file_extension = file_path
        .split('.')
        .last()
        .unwrap_or("tmp")
        .to_lowercase();
    
    let temp_file = temp_dir.join(format!(
        "onelake_sp_{}_{}.{}", 
        alias,
        chrono::Utc::now().timestamp_nanos_opt().unwrap_or(0),
        file_extension
    ));
    
    std::fs::write(&temp_file, content)
        .map_err(|e| ElusionError::Custom(format!("Failed to write temporary file: {}", e)))?;

    let aliased_df = CustomDataFrame::load(
        temp_file.to_str().unwrap(),
        alias
    ).await?;

    let _ = std::fs::remove_file(temp_file);

    Ok(CustomDataFrame {
        df: aliased_df.dataframe,
        table_alias: aliased_df.alias.clone(),
        from_table: aliased_df.alias.clone(),
        selected_columns: Vec::new(),
        alias_map: Vec::new(),
        aggregations: Vec::new(),
        group_by_columns: Vec::new(),
        where_conditions: Vec::new(),
        having_conditions: Vec::new(),
        order_by_columns: Vec::new(),
        limit_count: None,
        joins: Vec::new(),
        window_functions: Vec::new(),
        ctes: Vec::new(),
        subquery_source: None,
        set_operations: Vec::new(),
        query: String::new(),
        aggregated_df: None,
        union_tables: None,
        original_expressions: Vec::new(),
        needs_normalization: false,
        raw_selected_columns: Vec::new(),
        raw_group_by_columns: Vec::new(),
        raw_where_conditions: Vec::new(),
        raw_having_conditions: Vec::new(),
        raw_join_conditions: Vec::new(),
        raw_aggregations: Vec::new(),
        uses_group_by_all: false,
    })
}

// Write Parquet to OneLake using ABFSS path with Service Principal
#[cfg(feature = "fabric")]
pub async fn write_parquet_to_fabric_abfss_with_service_principal_impl(
    df: &CustomDataFrame,
    tenant_id: &str,
    client_id: &str,
    client_secret: &str,
    abfss_path: &str,
    file_path: &str,
) -> ElusionResult<()> {
    if !file_path.ends_with(".parquet") {
        return Err(ElusionError::Custom(
            "Invalid file extension. Parquet files must end with '.parquet'".to_string()
        ));
    }

    // Parse the ABFSS path
    let parsed = OneLakeClient::parse_abfss_path(abfss_path)?;

    // Create client with service principal credentials
    let mut client = OneLakeClient::new_with_service_principal(
        tenant_id.to_string(),
        client_id.to_string(),
        client_secret.to_string(),
        parsed.workspace_id,
        parsed.lakehouse_id,
        parsed.warehouse_id,
    ).await?;

    let batches: Vec<RecordBatch> = df.df.clone().collect().await
        .map_err(|e| ElusionError::Custom(format!("Failed to collect DataFrame: {}", e)))?;

    let props = WriterProperties::builder()
        .set_writer_version(WriterVersion::PARQUET_2_0)
        .set_compression(Compression::SNAPPY)
        .set_created_by("Elusion".to_string())
        .build();

    let mut buffer = Vec::new();
    {
        let schema: datafusion::arrow::datatypes::SchemaRef = df.df.schema().inner().clone();
        let mut writer = ArrowWriter::try_new(&mut buffer, schema.clone().into(), Some(props))
            .map_err(|e| ElusionError::Custom(format!("Failed to create Parquet writer: {}", e)))?;

        for batch in batches {
            writer.write(&batch)
                .map_err(|e| ElusionError::Custom(format!("Failed to write batch to Parquet: {}", e)))?;
        }
        writer.close()
            .map_err(|e| ElusionError::Custom(format!("Failed to close Parquet writer: {}", e)))?;
    }

    // Build full file path
    let full_file_path = if parsed.base_path == "Files" || parsed.base_path.is_empty() {
        file_path.to_string()
    } else {
        format!("{}/{}", parsed.base_path.trim_start_matches("Files/"), file_path)
    };

    client.upload_file(&full_file_path, buffer).await?;
    println!("Successfully wrote Parquet data to OneLake with Service Principal: {}", file_path);

    Ok(())
}