File size: 29,470 Bytes
f12ad36
 
 
 
 
 
 
 
 
0f0b6c8
f12ad36
0f0b6c8
f12ad36
 
 
afba74c
 
 
 
f12ad36
 
0f0b6c8
 
f12ad36
 
4293da0
f12ad36
 
 
 
 
 
 
0f0b6c8
f12ad36
 
 
 
 
0f0b6c8
 
 
 
 
 
f12ad36
 
0f0b6c8
 
 
 
 
f12ad36
 
 
 
 
 
 
 
 
4293da0
91182c7
4293da0
f12ad36
0f0b6c8
f12ad36
0f0b6c8
 
f12ad36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f0b6c8
 
 
 
f12ad36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2aeabe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4293da0
 
0f0b6c8
 
f12ad36
 
 
0f0b6c8
f12ad36
2aeabe5
f12ad36
 
 
0f0b6c8
f12ad36
 
 
 
2aeabe5
f12ad36
2aeabe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f12ad36
2aeabe5
 
 
 
 
 
 
 
 
 
 
 
f12ad36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f0b6c8
f12ad36
 
 
 
 
0f0b6c8
f12ad36
 
 
0f0b6c8
f12ad36
 
 
 
 
 
 
2aeabe5
 
f12ad36
0f0b6c8
f12ad36
 
0f0b6c8
f12ad36
0f0b6c8
f12ad36
 
 
 
 
 
 
 
 
0f0b6c8
f12ad36
 
0f0b6c8
f12ad36
 
 
 
0f0b6c8
f12ad36
0f0b6c8
f12ad36
 
 
 
 
 
 
 
 
 
 
 
0f0b6c8
f12ad36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f0b6c8
f12ad36
 
 
 
 
0f0b6c8
f12ad36
 
 
 
 
 
 
 
 
 
0f0b6c8
f12ad36
 
0f0b6c8
f12ad36
0f0b6c8
f12ad36
 
 
 
 
 
 
 
 
0f0b6c8
f12ad36
 
0f0b6c8
f12ad36
 
0f0b6c8
f12ad36
 
 
0f0b6c8
f12ad36
 
0f0b6c8
f12ad36
 
 
 
0f0b6c8
f12ad36
 
0f0b6c8
f12ad36
 
 
 
 
0f0b6c8
f12ad36
 
 
 
 
4293da0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f0b6c8
 
 
 
f12ad36
 
 
0f0b6c8
f12ad36
 
 
 
0f0b6c8
f12ad36
 
 
0f0b6c8
f12ad36
 
 
 
 
 
 
 
 
 
0f0b6c8
f12ad36
 
0f0b6c8
f12ad36
0f0b6c8
f12ad36
 
0f0b6c8
f12ad36
 
0f0b6c8
f12ad36
 
0f0b6c8
f12ad36
0f0b6c8
f12ad36
 
 
 
 
4293da0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f12ad36
 
 
0f0b6c8
f12ad36
 
 
 
 
0f0b6c8
f12ad36
 
 
 
 
 
 
 
 
 
0f0b6c8
f12ad36
 
0f0b6c8
f12ad36
0f0b6c8
f12ad36
 
0f0b6c8
f12ad36
 
0f0b6c8
f12ad36
 
 
 
 
 
0f0b6c8
f12ad36
 
 
 
 
 
 
 
 
0f0b6c8
 
 
 
f12ad36
 
 
 
 
 
 
0f0b6c8
f12ad36
 
 
 
 
 
0f0b6c8
f12ad36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f0b6c8
f12ad36
 
 
 
 
0f0b6c8
f12ad36
0f0b6c8
 
f12ad36
 
 
 
 
 
 
 
 
0f0b6c8
 
 
 
f12ad36
 
 
 
 
 
4293da0
f12ad36
 
 
 
 
 
 
 
4293da0
f12ad36
 
 
0f0b6c8
f12ad36
0f0b6c8
 
f12ad36
 
5a65404
91182c7
f12ad36
 
 
 
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
"""
Enhanced FastAPI server with high-performance Polars/DuckDB transformation engine.
Implements the ERP to CDF transformation logic with auto-detection capabilities.
"""

import logging
import tempfile
import os
from pathlib import Path
from typing import Dict, Any, Optional, List
from fastapi import FastAPI, File, UploadFile, Form, HTTPException, BackgroundTasks
from fastapi.responses import JSONResponse, FileResponse, RedirectResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
import uvicorn
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

from mapper.transformation_engine import (
    TransformationEngine,
    TransformationRequest,
    TransformationMode
)
from mapper.transformation_engine_pure import PureTransformationEngine
from mapper.data_processor import FileFormat
from mapper.models import EntityType

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Initialize FastAPI app (Swagger UI at /docs, ReDoc at /redoc)
app = FastAPI(
    title="ERP to CDF Transformation API v2.0",
    description="High-performance ERP data transformation using Polars and DuckDB",
    version="2.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
    swagger_ui_parameters={
        "persistAuthorization": True,       # keep auth between reloads
        "displayRequestDuration": True,     # show request timings
        "defaultModelsExpandDepth": -1      # collapse the schemas panel
    }
)

# Make Swagger UI the home page
@app.get("/", include_in_schema=False)
def home():
    return RedirectResponse(url="/docs")

# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Initialize transformation engines
transformation_engine = TransformationEngine()
pure_transformation_engine = PureTransformationEngine()

# ---------------------------
# Pydantic models for API
# ---------------------------

class TransformationRequestModel(BaseModel):
    """API model for transformation requests."""
    auto_select_erp: bool = Field(True, description="Auto-detect ERP system")
    auto_select_entity: bool = Field(True, description="Auto-detect entity type")
    entity: Optional[str] = Field(None, description="Entity type (if known)")
    erp: Optional[str] = Field(None, description="ERP system (if known)")
    data: Optional[List[Dict[str, Any]]] = Field(None, description="JSON data (alternative to file)")


class TransformationResponseModel(BaseModel):
    """API model for transformation responses."""
    success: bool
    data: Optional[List[Dict[str, Any]]] = None
    detected_erp: Optional[str] = None
    detected_entity: Optional[str] = None
    transformation_mode: Optional[str] = None
    confidence_score: Optional[float] = None
    message: Optional[str] = None
    column_mappings: Optional[Dict[str, str]] = None
    row_count: Optional[int] = None
    processing_time_ms: Optional[float] = None


class AnalysisResponseModel(BaseModel):
    """API model for data analysis responses."""
    column_info: Dict[str, Any]
    erp_entity_suggestions: List[Dict[str, Any]]
    available_entities: List[str]
    available_erps: List[str]
    processing_time_ms: Optional[float] = None


# ---------------------------
# Health / Info endpoints
# ---------------------------

@app.get("/health", tags=["Health"])
async def health_check():
    """Health check endpoint."""
    return {"status": "healthy", "version": "2.0.0", "engine": "Polars + DuckDB"}


@app.get("/entities", response_model=List[str], tags=["Information"])
async def get_entities():
    """Get list of supported entity types."""
    return [entity.value for entity in EntityType]


@app.get("/erps", response_model=List[str], tags=["Information"])
async def get_erps():
    """Get list of supported ERP systems."""
    return transformation_engine.template_loader.get_erp_names()


@app.get("/formats", response_model=List[str], tags=["Information"])
async def get_supported_formats():
    """Get list of supported file formats."""
    return [format.value for format in FileFormat]


@app.get("/formats/processing", tags=["Information"])
async def get_format_processing_methods():
    """Get processing methods for each file format (in-memory vs temp-file)."""
    processing_info = {}
    for format in FileFormat:
        method = transformation_engine.data_processor.get_processing_method(format)
        processing_info[format.value] = {
            "processing_method": method,
            "description": {
                "in-memory": "Fast, secure processing without temporary files",
                "temp-file": "Reliable processing using temporary files for complex formats"
            }.get(method, "Unknown processing method")
        }
    
    return {
        "formats": processing_info,
        "summary": {
            "in_memory_formats": [f.value for f in FileFormat if transformation_engine.data_processor.get_processing_method(f) == 'in-memory'],
            "temp_file_formats": [f.value for f in FileFormat if transformation_engine.data_processor.get_processing_method(f) == 'temp-file']
        }
    }


# ---------------------------
# Core transformation endpoints (Original)
# ---------------------------

@app.post("/transform", response_model=TransformationResponseModel, tags=["Transformation"])
async def transform_data(request: TransformationRequestModel):
    """Transform JSON data to CDF format.

    This endpoint accepts JSON data directly and transforms it according to the request parameters.
    Uses completely in-memory processing for better performance and security.
    """
    import time
    start_time = time.time()

    try:
        if not request.data:
            raise HTTPException(status_code=400, detail="No data provided")
        
        # Convert JSON data to bytes for in-memory processing (no temp files)
        import json
        json_bytes = json.dumps(request.data).encode('utf-8')
        
        # Create transformation request with bytes data
        transform_request = TransformationRequest(
            auto_select_erp=request.auto_select_erp,
            auto_select_entity=request.auto_select_entity,
            entity=request.entity,
            erp=request.erp,
            file_data=json_bytes,
            file_format=FileFormat.JSON
        )
        
        # Perform transformation (completely in-memory for JSON)
        result = transformation_engine.transform(transform_request)
        
        # Convert result to API response
        response_data = None
        if result.success and result.data is not None:
            response_data = transformation_engine.data_processor.to_dict(result.data)
        
        processing_time = (time.time() - start_time) * 1000
        
        return TransformationResponseModel(
            success=result.success,
            data=response_data,
            detected_erp=result.detected_erp,
            detected_entity=result.detected_entity,
            transformation_mode=result.transformation_mode.value if result.transformation_mode else None,
            confidence_score=result.confidence_score,
            message=result.message,
            column_mappings=result.column_mappings,
            row_count=len(response_data) if response_data else 0,
            processing_time_ms=processing_time
        )
                
    except Exception as e:
        logger.error(f"Transform data failed: {e}")
        raise HTTPException(status_code=500, detail=f"Transformation failed: {str(e)}")


@app.post("/transform/file", response_model=TransformationResponseModel, tags=["Transformation"])
async def transform_file(
    file: UploadFile = File(..., description="File to transform"),
    auto_select_erp: bool = Form(True, description="Auto-detect ERP system"),
    auto_select_entity: bool = Form(True, description="Auto-detect entity type"),
    entity: Optional[str] = Form(None, description="Entity type (if known)"),
    erp: Optional[str] = Form(None, description="ERP system (if known)"),
    output_format: str = Form("json", description="Output format (json, csv, parquet)")
):
    """Transform uploaded file to CDF format.

    This endpoint accepts file uploads and transforms them according to the request parameters.
    Supports CSV, Excel, JSON, and SQL files.
    """
    import time
    start_time = time.time()

    try:
        # Read file content
        file_content = await file.read()

        # Detect file format
        file_extension = Path(file.filename).suffix.lower()
        format_mapping = {
            '.csv': FileFormat.CSV,
            '.xlsx': FileFormat.EXCEL,
            '.xls': FileFormat.EXCEL,
            '.json': FileFormat.JSON,
            '.sql': FileFormat.SQL,
            '.parquet': FileFormat.PARQUET
        }

        if file_extension not in format_mapping:
            raise HTTPException(status_code=400, detail=f"Unsupported file format: {file_extension}")

        file_format = format_mapping[file_extension]

        # Create transformation request
        transform_request = TransformationRequest(
            auto_select_erp=auto_select_erp,
            auto_select_entity=auto_select_entity,
            entity=entity,
            erp=erp,
            file_data=file_content,
            file_format=file_format
        )

        # Perform transformation
        result = transformation_engine.transform(transform_request)

        # Convert result to API response
        response_data = None
        if result.success and result.data is not None:
            response_data = transformation_engine.data_processor.to_dict(result.data)

        processing_time = (time.time() - start_time) * 1000

        return TransformationResponseModel(
            success=result.success,
            data=response_data,
            detected_erp=result.detected_erp,
            detected_entity=result.detected_entity,
            transformation_mode=result.transformation_mode.value if result.transformation_mode else None,
            confidence_score=result.confidence_score,
            message=result.message,
            column_mappings=result.column_mappings,
            row_count=len(response_data) if response_data else 0,
            processing_time_ms=processing_time
        )

    except Exception as e:
        logger.error(f"Transform file failed: {e}")
        raise HTTPException(status_code=500, detail=f"File transformation failed: {str(e)}")


@app.post("/transform/file/download", tags=["Transformation"])
async def transform_file_download(
    background_tasks: BackgroundTasks,
    file: UploadFile = File(..., description="File to transform"),
    auto_select_erp: bool = Form(True, description="Auto-detect ERP system"),
    auto_select_entity: bool = Form(True, description="Auto-detect entity type"),
    entity: Optional[str] = Form(None, description="Entity type (if known)"),
    erp: Optional[str] = Form(None, description="ERP system (if known)"),
    output_format: str = Form("csv", description="Output format (csv, json, parquet)")
):
    """Transform uploaded file and return as downloadable file.

    This endpoint transforms the file and returns the result as a downloadable file.
    """
    try:
        # Read file content
        file_content = await file.read()

        # Detect file format
        file_extension = Path(file.filename).suffix.lower()
        format_mapping = {
            '.csv': FileFormat.CSV,
            '.xlsx': FileFormat.EXCEL,
            '.xls': FileFormat.EXCEL,
            '.json': FileFormat.JSON,
            '.sql': FileFormat.SQL,
            '.parquet': FileFormat.PARQUET
        }

        if file_extension not in format_mapping:
            raise HTTPException(status_code=400, detail=f"Unsupported file format: {file_extension}")

        file_format = format_mapping[file_extension]

        # Create transformation request
        transform_request = TransformationRequest(
            auto_select_erp=auto_select_erp,
            auto_select_entity=auto_select_entity,
            entity=entity,
            erp=erp,
            file_data=file_content,
            file_format=file_format
        )

        # Perform transformation
        result = transformation_engine.transform(transform_request)

        if not result.success:
            raise HTTPException(status_code=400, detail=result.message)

        # Create output file
        output_format_enum = FileFormat(output_format.lower())
        output_filename = f"transformed_{Path(file.filename).stem}_cdf.{output_format}"

        with tempfile.NamedTemporaryFile(delete=False, suffix=f".{output_format}") as temp_file:
            temp_path = temp_file.name

        # Export transformed data
        transformation_engine.data_processor.export_dataframe(
            result.data, temp_path, output_format_enum
        )

        # Schedule cleanup
        background_tasks.add_task(cleanup_temp_file, temp_path)

        return FileResponse(
            path=temp_path,
            filename=output_filename,
            media_type="application/octet-stream"
        )

    except Exception as e:
        logger.error(f"Transform file download failed: {e}")
        raise HTTPException(status_code=500, detail=f"File transformation failed: {str(e)}")


# ---------------------------
# Pure LLM transformation endpoints (NEW)
# ---------------------------

@app.post("/llm_pure/transform", response_model=TransformationResponseModel, tags=["Pure LLM Transformation"])
async def pure_llm_transform_data(request: TransformationRequestModel):
    """Transform JSON data to CDF format using Pure LLM approach.

    This endpoint uses only LLM-based mapping when ERP or Entity is unknown, 
    with enhanced template context and 5 retry attempts.
    """
    import time
    start_time = time.time()

    try:
        if not request.data:
            raise HTTPException(status_code=400, detail="No data provided")
        
        # Convert JSON data to bytes for in-memory processing
        import json
        json_bytes = json.dumps(request.data).encode('utf-8')
        
        # Create transformation request with bytes data
        transform_request = TransformationRequest(
            auto_select_erp=request.auto_select_erp,
            auto_select_entity=request.auto_select_entity,
            entity=request.entity,
            erp=request.erp,
            file_data=json_bytes,
            file_format=FileFormat.JSON
        )
        
        # Perform Pure LLM transformation
        result = pure_transformation_engine.transform(transform_request)
        
        # Convert result to API response
        response_data = None
        if result.success and result.data is not None:
            response_data = pure_transformation_engine.data_processor.to_dict(result.data)
        
        processing_time = (time.time() - start_time) * 1000
        
        return TransformationResponseModel(
            success=result.success,
            data=response_data,
            detected_erp=result.detected_erp,
            detected_entity=result.detected_entity,
            transformation_mode=result.transformation_mode.value if result.transformation_mode else None,
            confidence_score=result.confidence_score,
            message=result.message,
            column_mappings=result.column_mappings,
            row_count=len(response_data) if response_data else 0,
            processing_time_ms=processing_time
        )
                
    except Exception as e:
        logger.error(f"Pure LLM transform data failed: {e}")
        raise HTTPException(status_code=500, detail=f"Pure LLM transformation failed: {str(e)}")


@app.post("/llm_pure/transform/file", response_model=TransformationResponseModel, tags=["Pure LLM Transformation"])
async def pure_llm_transform_file(
    file: UploadFile = File(..., description="File to transform"),
    auto_select_erp: bool = Form(True, description="Auto-detect ERP system"),
    auto_select_entity: bool = Form(True, description="Auto-detect entity type"),
    entity: Optional[str] = Form(None, description="Entity type (if known)"),
    erp: Optional[str] = Form(None, description="ERP system (if known)"),
    output_format: str = Form("json", description="Output format (json, csv, parquet)")
):
    """Transform uploaded file to CDF format using Pure LLM approach.

    This endpoint uses only LLM-based mapping when ERP or Entity is unknown,
    with enhanced template context and 5 retry attempts.
    """
    import time
    start_time = time.time()

    try:
        # Read file content
        file_content = await file.read()

        # Detect file format
        file_extension = Path(file.filename).suffix.lower()
        format_mapping = {
            '.csv': FileFormat.CSV,
            '.xlsx': FileFormat.EXCEL,
            '.xls': FileFormat.EXCEL,
            '.json': FileFormat.JSON,
            '.sql': FileFormat.SQL,
            '.parquet': FileFormat.PARQUET
        }

        if file_extension not in format_mapping:
            raise HTTPException(status_code=400, detail=f"Unsupported file format: {file_extension}")

        file_format = format_mapping[file_extension]

        # Create transformation request
        transform_request = TransformationRequest(
            auto_select_erp=auto_select_erp,
            auto_select_entity=auto_select_entity,
            entity=entity,
            erp=erp,
            file_data=file_content,
            file_format=file_format
        )

        # Perform Pure LLM transformation
        result = pure_transformation_engine.transform(transform_request)

        # Convert result to API response
        response_data = None
        if result.success and result.data is not None:
            response_data = pure_transformation_engine.data_processor.to_dict(result.data)

        processing_time = (time.time() - start_time) * 1000

        return TransformationResponseModel(
            success=result.success,
            data=response_data,
            detected_erp=result.detected_erp,
            detected_entity=result.detected_entity,
            transformation_mode=result.transformation_mode.value if result.transformation_mode else None,
            confidence_score=result.confidence_score,
            message=result.message,
            column_mappings=result.column_mappings,
            row_count=len(response_data) if response_data else 0,
            processing_time_ms=processing_time
        )

    except Exception as e:
        logger.error(f"Pure LLM transform file failed: {e}")
        raise HTTPException(status_code=500, detail=f"Pure LLM file transformation failed: {str(e)}")


@app.post("/llm_pure/transform/file/download", tags=["Pure LLM Transformation"])
async def pure_llm_transform_file_download(
    background_tasks: BackgroundTasks,
    file: UploadFile = File(..., description="File to transform"),
    auto_select_erp: bool = Form(True, description="Auto-detect ERP system"),
    auto_select_entity: bool = Form(True, description="Auto-detect entity type"),
    entity: Optional[str] = Form(None, description="Entity type (if known)"),
    erp: Optional[str] = Form(None, description="ERP system (if known)"),
    output_format: str = Form("csv", description="Output format (csv, json, parquet)")
):
    """Transform uploaded file and return as downloadable file using Pure LLM approach.

    This endpoint uses only LLM-based mapping when ERP or Entity is unknown,
    with enhanced template context and 5 retry attempts.
    """
    try:
        # Read file content
        file_content = await file.read()

        # Detect file format
        file_extension = Path(file.filename).suffix.lower()
        format_mapping = {
            '.csv': FileFormat.CSV,
            '.xlsx': FileFormat.EXCEL,
            '.xls': FileFormat.EXCEL,
            '.json': FileFormat.JSON,
            '.sql': FileFormat.SQL,
            '.parquet': FileFormat.PARQUET
        }

        if file_extension not in format_mapping:
            raise HTTPException(status_code=400, detail=f"Unsupported file format: {file_extension}")

        file_format = format_mapping[file_extension]

        # Create transformation request
        transform_request = TransformationRequest(
            auto_select_erp=auto_select_erp,
            auto_select_entity=auto_select_entity,
            entity=entity,
            erp=erp,
            file_data=file_content,
            file_format=file_format
        )

        # Perform Pure LLM transformation
        result = pure_transformation_engine.transform(transform_request)

        if not result.success:
            raise HTTPException(status_code=400, detail=result.message)

        # Create output file
        output_format_enum = FileFormat(output_format.lower())
        output_filename = f"pure_llm_transformed_{Path(file.filename).stem}_cdf.{output_format}"

        with tempfile.NamedTemporaryFile(delete=False, suffix=f".{output_format}") as temp_file:
            temp_path = temp_file.name

        # Export transformed data
        pure_transformation_engine.data_processor.export_dataframe(
            result.data, temp_path, output_format_enum
        )

        # Schedule cleanup
        background_tasks.add_task(cleanup_temp_file, temp_path)

        return FileResponse(
            path=temp_path,
            filename=output_filename,
            media_type="application/octet-stream"
        )

    except Exception as e:
        logger.error(f"Pure LLM transform file download failed: {e}")
        raise HTTPException(status_code=500, detail=f"Pure LLM file transformation failed: {str(e)}")


# ---------------------------
# Analysis / Validation
# ---------------------------

@app.post("/analyze", response_model=AnalysisResponseModel, tags=["Analysis"])
async def analyze_data(file: UploadFile = File(..., description="File to analyze")):
    """Analyze uploaded file and provide insights.

    This endpoint analyzes the file structure and suggests possible ERP/entity combinations.
    """
    import time
    start_time = time.time()

    try:
        # Read file content
        file_content = await file.read()

        # Detect file format
        file_extension = Path(file.filename).suffix.lower()
        format_mapping = {
            '.csv': FileFormat.CSV,
            '.xlsx': FileFormat.EXCEL,
            '.xls': FileFormat.EXCEL,
            '.json': FileFormat.JSON,
            '.sql': FileFormat.SQL,
            '.parquet': FileFormat.PARQUET
        }

        if file_extension not in format_mapping:
            raise HTTPException(status_code=400, detail=f"Unsupported file format: {file_extension}")

        file_format = format_mapping[file_extension]

        # Analyze data
        analysis_result = transformation_engine.analyze_data(file_content, file_format)

        if "error" in analysis_result:
            raise HTTPException(status_code=400, detail=analysis_result["error"])

        processing_time = (time.time() - start_time) * 1000
        analysis_result["processing_time_ms"] = processing_time

        return AnalysisResponseModel(**analysis_result)

    except Exception as e:
        logger.error(f"Analyze data failed: {e}")
        raise HTTPException(status_code=500, detail=f"Analysis failed: {str(e)}")


@app.post("/llm_pure/analyze", response_model=AnalysisResponseModel, tags=["Pure LLM Analysis"])
async def pure_llm_analyze_data(file: UploadFile = File(..., description="File to analyze")):
    """Analyze uploaded file using Pure LLM approach.

    This endpoint analyzes the file structure for Pure LLM transformation.
    """
    import time
    start_time = time.time()

    try:
        # Read file content
        file_content = await file.read()

        # Detect file format
        file_extension = Path(file.filename).suffix.lower()
        format_mapping = {
            '.csv': FileFormat.CSV,
            '.xlsx': FileFormat.EXCEL,
            '.xls': FileFormat.EXCEL,
            '.json': FileFormat.JSON,
            '.sql': FileFormat.SQL,
            '.parquet': FileFormat.PARQUET
        }

        if file_extension not in format_mapping:
            raise HTTPException(status_code=400, detail=f"Unsupported file format: {file_extension}")

        file_format = format_mapping[file_extension]

        # Analyze data using Pure LLM engine
        analysis_result = pure_transformation_engine.analyze_data(file_content, file_format)

        if "error" in analysis_result:
            raise HTTPException(status_code=400, detail=analysis_result["error"])

        processing_time = (time.time() - start_time) * 1000
        analysis_result["processing_time_ms"] = processing_time

        return AnalysisResponseModel(**analysis_result)

    except Exception as e:
        logger.error(f"Pure LLM analyze data failed: {e}")
        raise HTTPException(status_code=500, detail=f"Pure LLM analysis failed: {str(e)}")


@app.post("/validate", tags=["Validation"])
async def validate_data(file: UploadFile = File(..., description="File to validate")):
    """Validate file structure and content.

    This endpoint validates the file can be loaded and provides basic statistics.
    """
    try:
        # Read file content
        file_content = await file.read()

        # Detect file format
        file_extension = Path(file.filename).suffix.lower()
        format_mapping = {
            '.csv': FileFormat.CSV,
            '.xlsx': FileFormat.EXCEL,
            '.xls': FileFormat.EXCEL,
            '.json': FileFormat.JSON,
            '.sql': FileFormat.SQL,
            '.parquet': FileFormat.PARQUET
        }

        if file_extension not in format_mapping:
            raise HTTPException(status_code=400, detail=f"Unsupported file format: {file_extension}")

        file_format = format_mapping[file_extension]

        # Load and validate data
        df = transformation_engine.data_processor.load_from_bytes(file_content, file_format, file.filename)

        # Get column info
        column_info = transformation_engine.data_processor.get_column_info(df)

        return {
            "valid": True,
            "file_format": file_format.value,
            "column_info": column_info,
            "message": "File is valid and can be processed"
        }

    except Exception as e:
        logger.error(f"Validate data failed: {e}")
        return {
            "valid": False,
            "error": str(e),
            "message": "File validation failed"
        }


# ---------------------------
# Template utilities
# ---------------------------

@app.get("/template/erp/{erp}/entity/{entity}", tags=["Template"])
async def get_template_mapping(erp: str, entity: str):
    """Get template mapping for specific ERP and entity."""
    try:
        mapping = transformation_engine.template_loader.get_entity_mapping(erp, entity)
        if not mapping:
            raise HTTPException(status_code=404, detail=f"No mapping found for {erp} -> {entity}")

        return {
            "erp": erp,
            "entity": entity,
            "mapping": mapping,
            "cdf_schema": transformation_engine.template_loader.get_cdf_schema(entity)
        }

    except Exception as e:
        logger.error(f"Get template mapping failed: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/template/entity/{entity}/schema", tags=["Template"])
async def get_entity_schema(entity: str):
    """Get CDF schema for specific entity."""
    try:
        schema = transformation_engine.template_loader.get_cdf_schema(entity)
        return {
            "entity": entity,
            "cdf_schema": schema,
            "field_count": len(schema)
        }

    except Exception as e:
        logger.error(f"Get entity schema failed: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# ---------------------------
# Background task for cleanup
# ---------------------------

def cleanup_temp_file(file_path: str):
    """Clean up temporary file."""
    try:
        os.unlink(file_path)
        logger.info(f"Cleaned up temporary file: {file_path}")
    except OSError as e:
        logger.warning(f"Failed to clean up temporary file {file_path}: {e}")


# ---------------------------
# Startup / Shutdown
# ---------------------------

@app.on_event("startup")
async def startup_event():
    """Startup event handler."""
    logger.info("ERP to CDF Transformation API v2.0 starting up...")
    logger.info(f"Supported ERP systems: {len(transformation_engine.template_loader.get_erp_names())}")
    logger.info(f"Supported entities: {len([e.value for e in EntityType])}")
    logger.info("Pure LLM transformation engine initialized")
    logger.info("API ready for high-performance transformations!")


@app.on_event("shutdown")
async def shutdown_event():
    """Shutdown event handler."""
    logger.info("ERP to CDF Transformation API v2.0 shutting down...")
    transformation_engine.close()
    pure_transformation_engine.close()
    logger.info("Shutdown complete.")


# ---------------------------
# Main entry point
# ---------------------------

if __name__ == "__main__":
    uvicorn.run(
        "app:app",
        host="127.0.0.1",
        port=8000,
        reload=True,
        log_level="info"
    )