File size: 33,132 Bytes
61e7b06
 
 
 
52de8f8
61e7b06
 
52de8f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61e7b06
e26711e
61e7b06
 
e26711e
 
61e7b06
8c9119d
39a5cd5
 
 
 
61e7b06
 
 
 
 
 
 
 
8c9119d
 
61e7b06
 
e26711e
 
 
 
 
 
 
cc5c9eb
e26711e
 
 
 
 
cc5c9eb
e26711e
 
8c9119d
 
e26711e
8c9119d
e26711e
 
 
 
8c9119d
61e7b06
 
e26711e
 
 
 
8c9119d
 
 
 
61e7b06
e26711e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61e7b06
e26711e
 
61e7b06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b625fd8
 
 
61e7b06
 
 
 
53287e1
 
 
 
 
 
 
 
 
 
61e7b06
 
 
 
53287e1
 
 
 
 
 
 
 
61e7b06
 
 
 
52de8f8
 
 
 
 
 
 
 
61e7b06
 
52de8f8
 
61e7b06
52de8f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61e7b06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52de8f8
 
61e7b06
52de8f8
 
 
 
 
e26711e
 
 
52de8f8
e26711e
52de8f8
 
 
 
 
 
 
 
 
 
 
 
 
e26711e
 
 
52de8f8
e26711e
 
61e7b06
 
b625fd8
 
 
 
 
 
 
 
 
8c9119d
 
 
 
b625fd8
 
 
 
 
 
 
d428254
 
 
b625fd8
 
53287e1
b625fd8
 
 
 
 
 
 
74f3fe5
b625fd8
 
 
 
52de8f8
 
 
74f3fe5
e1b7040
52de8f8
 
b625fd8
74f3fe5
 
 
 
 
 
52de8f8
 
74f3fe5
b625fd8
52de8f8
 
 
 
 
b625fd8
52de8f8
 
39a5cd5
 
 
 
 
 
74f3fe5
53287e1
 
 
 
 
52de8f8
39a5cd5
52de8f8
39a5cd5
52de8f8
39a5cd5
 
e1b7040
52de8f8
 
e1b7040
 
53287e1
 
 
 
 
 
e1b7040
52de8f8
39a5cd5
 
52de8f8
e1b7040
 
 
52de8f8
e1b7040
 
 
 
 
 
 
 
39a5cd5
e1b7040
 
 
 
 
 
53287e1
 
 
 
 
e1b7040
 
 
39a5cd5
e1b7040
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53287e1
 
 
 
 
 
 
 
e1b7040
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39a5cd5
e1b7040
 
 
 
 
 
 
 
39a5cd5
 
52de8f8
e1b7040
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39a5cd5
e1b7040
 
 
 
 
 
 
39a5cd5
e1b7040
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52de8f8
e1b7040
52de8f8
e1b7040
52de8f8
 
 
e1b7040
 
52de8f8
e1b7040
 
 
52de8f8
e1b7040
 
 
52de8f8
e1b7040
 
 
52de8f8
 
 
e1b7040
 
 
 
 
 
 
52de8f8
e1b7040
 
 
 
 
 
 
52de8f8
e1b7040
 
 
 
 
 
 
52de8f8
 
e1b7040
52de8f8
 
e1b7040
52de8f8
 
e1b7040
52de8f8
b625fd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1b7040
b625fd8
 
 
 
 
 
 
 
53287e1
 
 
b625fd8
 
53287e1
 
b625fd8
 
 
 
53287e1
 
 
 
74f3fe5
 
 
 
 
 
 
 
53287e1
 
 
 
74f3fe5
53287e1
b625fd8
e1b7040
 
 
 
 
 
 
 
 
 
39a5cd5
e1b7040
 
53287e1
e1b7040
52de8f8
 
 
 
 
 
53287e1
b625fd8
 
52de8f8
 
53287e1
 
 
 
 
 
 
 
52de8f8
 
 
 
e1b7040
39a5cd5
e1b7040
39a5cd5
 
 
 
 
e1b7040
 
 
 
 
 
 
 
 
 
b625fd8
 
52de8f8
b625fd8
53287e1
b625fd8
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
"""
Data generation components and UI
"""

import io
import json
import pandas as pd
import requests
import streamlit as st
import time
from config.settings import (
    API_BASE_URL, 
    DEFAULT_NUM_RECORDS, 
    MAX_RECORDS, 
    DEFAULT_TEMPERATURE, 
    DEFAULT_MAX_TOKENS,
    OUTPUT_FORMATS,
    PROGRESS_STEPS,
    GENERATION_API_ENDPOINT, 
    API_TIMEOUT
)
from utils.aws_s3 import download_file_from_s3_url
from utils.data_processing import (
    validate_api_key_with_server,
    generate_sample_data, 
    calculate_generation_metrics,
    create_download_data,
    get_api_headers
)
from utils.session_state import clear_api_state
from utils.logging_config import get_logger, log_api_request, log_api_response, log_generation_metrics

# Initialize logger
logger = get_logger(__name__)


def render_api_key_input():
    """Render API key input and validation"""
    api_key = st.text_input(
        "πŸ”‘ Syncora API Key",
        type="password",
        placeholder="Enter your API key (e.g., sync-xxxxxxxxxxxx)",
        help="Get your API key from the Syncora dashboard. Your key is encrypted before transmission for security.",
        key="api_key_input"
    )
    
    # Validate API key button
    col_validate, col_status = st.columns([1, 2])
    
    with col_validate:
        validate_clicked = st.button(
            "πŸ” Validate",
            key="validate_api_key",
            help="Validate API key with server using encrypted transmission",
            use_container_width=True
        )
    
    # Handle validation
    if validate_clicked and api_key:
        with st.spinner("Validating API key (encrypting and sending securely)..."):
            validation_result = validate_api_key_with_server(api_key)
            st.session_state.api_validation = validation_result
            if validation_result.get("valid", False):
                st.session_state.validated_api_key = api_key
            st.session_state.validation_attempted = True
            st.rerun()  # Force rerun to update UI immediately
    elif validate_clicked and not api_key:
        st.session_state.api_validation = {"valid": False, "message": "Please enter an API key first"}
        st.session_state.validation_attempted = True
    
    # Reset validation status when key changes
    if api_key != st.session_state.get('last_api_key', ''):
        st.session_state.last_api_key = api_key
        # Reset validation status when key changes (but don't show error)
        if not api_key:
            st.session_state.api_validation = {"valid": False, "message": ""}
            st.session_state.validation_attempted = False
        elif api_key != st.session_state.get('validated_api_key', ''):
            # Key changed from a previously validated key
            st.session_state.api_validation = {"valid": False, "message": ""}
            st.session_state.validation_attempted = False
    
    # Display validation status - only if validation was attempted
    with col_status:
        if (hasattr(st.session_state, 'validation_attempted') and 
            st.session_state.validation_attempted and 
            hasattr(st.session_state, 'api_validation') and 
            st.session_state.api_validation):
            
            validation = st.session_state.api_validation
            if validation["valid"]:
                message = validation["message"]
                if "response_time" in validation:
                    message += f" ({validation['response_time']}s)"
                st.markdown(f'<div class="status-indicator status-valid">βœ… {message}</div>', 
                           unsafe_allow_html=True)
            else:
                st.markdown(f'<div class="status-indicator status-invalid">❌ {validation["message"]}</div>', 
                           unsafe_allow_html=True)
        else:
            # Show neutral state when no validation attempted
            st.markdown('<div class="status-indicator status-pending">πŸ’‘ Click validate to check API key</div>', 
                       unsafe_allow_html=True)
    
    return api_key


def render_generation_settings():
    """Render generation settings"""
    # Number of Records
    num_records = st.number_input(
        "Number of Records",
        min_value=1,
        max_value=MAX_RECORDS,
        value=DEFAULT_NUM_RECORDS,
        step=5,
        help="Number of data records to generate"
    )
    
    return {
        "num_records": num_records,
        "temperature": DEFAULT_TEMPERATURE,
        "max_tokens": DEFAULT_MAX_TOKENS,
        "include_metadata": True
    }


def render_generation_progress():
    """Show generation progress with real API call tracking"""
    # Create placeholder for real-time status updates
    progress_placeholder = st.empty()
    status_placeholder = st.empty()
    
    # Initial status
    with progress_placeholder:
        st.info("πŸ€– Initializing data generation request...")
    
    return progress_placeholder, status_placeholder


def render_results_display(generated_data, num_records):
    """Display generation results"""
    # Get actual record count from the data
    actual_records = generated_data.get("records_count", num_records)
    if "dataframe" in generated_data:
        actual_records = len(generated_data["dataframe"])
    elif "data" in generated_data:
        actual_records = len(generated_data["data"])
    
    st.success(f"βœ… Successfully generated {actual_records} records in {st.session_state.output_format.upper()} format!")
    
    # Display results
    st.markdown("### πŸ“Š Generated Results")
    
    if generated_data.get("format") == "tabular" or "dataframe" in generated_data:
        # Check if we have a DataFrame or need to create one
        if "dataframe" in generated_data:
            df_results = generated_data["dataframe"]
        else:
            df_results = pd.DataFrame(generated_data["data"])
        
        # Display the DataFrame
        st.dataframe(df_results, use_container_width=True, height=400)
        
        # Download buttons section
        st.markdown("### πŸ“₯ Download Options")
        
        # If we have the original file content from S3, use it for download
        if "file_content" in generated_data and "filename" in generated_data:
            # Original file download
            original_filename = generated_data["filename"]
            file_extension = original_filename.split('.')[-1].lower()
            
            col_original, col_csv, col_excel = st.columns(3)
            
            with col_original:
                st.download_button(
                    f"πŸ“₯ Download Original ({file_extension.upper()})",
                    generated_data["file_content"],
                    original_filename,
                    f"application/{file_extension}",
                    use_container_width=True,
                    help="Download the file exactly as generated by the API"
                )
            
            # CSV download
            with col_csv:
                csv_data = df_results.to_csv(index=False)
                st.download_button(
                    "πŸ“₯ Download CSV",
                    csv_data,
                    f"syncora_data_{int(time.time())}.csv",
                    "text/csv",
                    use_container_width=True,
                    help="Download as CSV format"
                )
            
            # Excel download
            with col_excel:
                excel_buffer = io.BytesIO()
                with pd.ExcelWriter(excel_buffer, engine='openpyxl') as writer:
                    df_results.to_excel(writer, index=False, sheet_name='Generated Data')
                excel_data = excel_buffer.getvalue()
                
                st.download_button(
                    "πŸ“₯ Download Excel",
                    excel_data,
                    f"syncora_data_{int(time.time())}.xlsx",
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    use_container_width=True,
                    help="Download as Excel format"
                )
                
        else:
            # Fallback to creating download data
            download_data = create_download_data(generated_data)
            col_csv, col_excel = st.columns(2)
            
            with col_csv:
                st.download_button(
                    "πŸ“₯ Download CSV",
                    download_data["csv"],
                    f"syncora_data_{int(time.time())}.csv",
                    "text/csv",
                    use_container_width=True
                )
            with col_excel:
                st.download_button(
                    "πŸ“₯ Download Excel",
                    download_data["excel"],
                    f"syncora_data_{int(time.time())}.xlsx",
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    use_container_width=True
                )
                
        # Show S3 URL if available
        if "s3_url" in generated_data:
            st.markdown("### πŸ”— Direct Access")
            st.info(f"**Generated File URL:** {generated_data['s3_url']}")
            
    else:  # JSONL format
        # Show preview
        jsonl_preview = []
        for record in generated_data["data"][:5]:  # Show first 5 records
            jsonl_preview.append(json.dumps(record, indent=2))
        
        st.code("\n\n".join(jsonl_preview), language="json")
        
        if len(generated_data["data"]) > 5:
            st.info(f"Showing first 5 records out of {len(generated_data['data'])} total records")
        
        # Download JSONL
        download_data = create_download_data(generated_data)
        st.download_button(
            "πŸ“₯ Download JSONL",
            download_data["jsonl"],
            f"syncora_data_{int(time.time())}.jsonl",
            "application/json",
            use_container_width=True
        )


def render_generation_metrics(generated_data):
    """Display generation metrics"""
    st.markdown("### πŸ“ˆ Generation Metrics")
    
    metrics = calculate_generation_metrics(generated_data)
    
    col_met1, col_met2, col_met3, col_met4 = st.columns(4)
    
    with col_met1:
        st.metric("Records", metrics["total_records"])
    with col_met2:
        st.metric("Avg Confidence", f"{metrics['avg_confidence']:.2f}")
    with col_met3:
        format_display = metrics.get("format", "tabular").title()
        st.metric("Format", format_display)
    with col_met4:
        # Show file size if available
        if "file_content" in generated_data:
            file_size_mb = len(generated_data["file_content"]) / (1024 * 1024)
            st.metric("File Size", f"{file_size_mb:.2f} MB")
        elif "api_authenticated" in metrics:
            status = "βœ… Yes" if metrics["api_authenticated"] else "❌ No"
            st.metric("API Auth", status)
        else:
            st.metric("Total Tokens", f"{metrics.get('total_tokens', 0):,}")
    
    # Additional info row if file was downloaded from S3
    if generated_data.get("s3_url"):
        st.markdown("---")
        col_extra1, col_extra2, col_extra3 = st.columns(3)
        with col_extra1:
            if "filename" in generated_data:
                st.metric("Original File", generated_data["filename"])
        with col_extra2:
            st.metric("Source", "S3 Download")
        with col_extra3:
            if metrics.get("total_tokens"):
                st.metric("Total Tokens", f"{metrics['total_tokens']:,}")
    elif metrics.get("api_authenticated"):
        st.markdown("---")
        col_extra1, col_extra2 = st.columns(2)
        with col_extra1:
            st.metric("Total Tokens", f"{metrics.get('total_tokens', 0):,}")
        with col_extra2:
            st.metric("Auth Method", "x-api-key")


def render_api_key_validation_step():
    """Render API key validation as the first required step"""
    # Check if we already have a validated API key
    is_complete = (st.session_state.get('api_validation', {}).get('valid', False) and 
                   st.session_state.get('validated_api_key', ''))
    
    if is_complete:
        st.markdown('<h3 class="section-title step-complete">πŸ”‘ Step 1: API Key Validation βœ…</h3>', unsafe_allow_html=True)
        st.success(f"βœ… API Key validated successfully!")
          # Show option to change API key
        if st.button("πŸ”„ Change API Key", help="Use a different API key", key="change_api_key_btn"):
            # Clear all API-related session state
            clear_api_state()
            st.rerun()
        
        return True
    else:
        st.markdown('<h3 class="section-title step-incomplete">πŸ”‘ Step 1: API Key Validation</h3>', unsafe_allow_html=True)
        # Show API key input and validation
        render_api_key_input()
        # Return the current validation state from session state, ensuring it's a boolean
        return bool(st.session_state.get('api_validation', {}).get('valid', False) and 
                    st.session_state.get('validated_api_key', ''))


def call_generation_api(file_link, config, api_key, file_metadata=None, progress_placeholder=None, status_placeholder=None):
    """
    Call the generation API with file link and configuration
    
    Args:
        file_link (str): AWS S3 link to the uploaded file
        config (dict): All configuration settings including generation settings
        api_key (str): Validated API key
        file_metadata (dict): File metadata including size and row count
    
    Returns:
        dict: Generated data response
    """
    # Construct API URL and payload
    api_url = f"{API_BASE_URL}/{GENERATION_API_ENDPOINT}"
    payload = {
        "fileUrl": file_link,
        "type": "Tabular",
        "numberOfRows": config.get("num_rows", 100)
    }
    
    # Add file metadata if available
    if file_metadata:
        payload["fileSizeBytes"] = file_metadata.get("file_size_bytes", 0)
        payload["sourceFileRows"] = file_metadata.get("num_rows", 0)
        st.info(f"πŸ“Š Including file metadata: {file_metadata.get('num_rows', 0)} rows, {file_metadata.get('file_size_bytes', 0)} bytes")
    
    # Add target column if specified
    if config.get("target_column", "").strip():
        payload["targetColumn"] = config["target_column"].strip()
    
    # Prepare encrypted headers
    try:
        headers = get_api_headers(api_key)
    except ValueError as e:
        return {"success": False, "error": f"Failed to prepare headers: {str(e)}"}
    
    # Make API call
    try:
        # Log API request
        log_api_request(logger, "POST", api_url, {
            "numberOfRows": payload.get('numberOfRows'),
            "type": payload.get('type'),
            "targetColumn": payload.get('targetColumn')
        })
        
        # Update progress if available
        if status_placeholder:
            with status_placeholder:
                st.info("🌐 Making API call...")
        
        st.info("πŸ”„ Making API call...")
        start_time = time.time()
        response = requests.post(api_url, json=payload, headers=headers, timeout=API_TIMEOUT)
        response_time = time.time() - start_time
        
        # Log API response
        log_api_response(logger, response.status_code, response_time, response.status_code == 200)
        
        # Handle response
        if response.status_code == 200:
            try:
                result = response.json()
                
                # Update progress
                if status_placeholder:
                    with status_placeholder:
                        st.success("βœ… API call successful!")
                
                st.success("βœ… API call successful!")
                
                # Log successful response for monitoring
                logger.info(f"Generation API returned {len(result.keys())} result keys")
                
                # Check for different possible URL keys in the response
                # First check if there's a nested data object
                data_obj = result.get("data", result)
                
                url_keys = ["fileUrl", "s3Url", "downloadUrl", "file_url", "s3_url", "download_url", "url"]
                s3_url = None
                
                # Check in the data object first, then in the main result
                for obj in [data_obj, result]:
                    for key in url_keys:
                        if key in obj:
                            s3_url = obj[key]
                            logger.info(f"Generated file URL found: {key}")
                            st.info(f"πŸ“Ž Found generated file URL")
                            break
                    if s3_url:
                        break
                
                if s3_url:
                    # Update progress
                    if status_placeholder:
                        with status_placeholder:
                            st.info("πŸ“₯ Downloading generated file from S3...")
                    
                    st.info("πŸ“₯ Downloading generated file from S3...")
                    
                    # Print S3 URL to console
                    logger.info(f"Attempting to download from S3 URL")
                    
                    # Try to download the file from S3
                    download_result = download_file_from_s3_url(s3_url)
                    
                    if download_result["success"]:
                        # Parse the downloaded file content
                        try:
                            file_content = download_result["content"]
                            filename = download_result["filename"]
                            st.success(f"βœ… Downloaded file: {filename}")
                            
                            # Determine file type and parse accordingly
                            if filename.lower().endswith('.csv'):
                                df = pd.read_csv(io.BytesIO(file_content))
                            elif filename.lower().endswith(('.xlsx', '.xls')):
                                df = pd.read_excel(io.BytesIO(file_content))
                            elif filename.lower().endswith('.json'):
                                df = pd.read_json(io.BytesIO(file_content))
                            else:
                                # Try CSV as default
                                df = pd.read_csv(io.BytesIO(file_content))
                            
                            # Convert DataFrame to list of dictionaries
                            data_records = df.to_dict('records')
                            
                            # Update final progress
                            if progress_placeholder:
                                with progress_placeholder:
                                    st.success("πŸŽ‰ Data generation completed successfully!")
                            if status_placeholder:
                                with status_placeholder:
                                    st.success(f"βœ… Generated {len(data_records)} records successfully!")
                            
                            st.info(f"πŸ“Š Parsed {len(data_records)} records from downloaded file")
                            
                            return {
                                "data": data_records,
                                "dataframe": df,
                                "success": True,
                                "records_count": len(data_records),
                                "api_response": result,
                                "s3_url": s3_url,
                                "filename": filename,
                                "file_content": file_content,
                                "format": "tabular"
                            }
                            
                        except Exception as parse_error:
                            st.error(f"❌ Failed to parse downloaded file: {str(parse_error)}")
                            if st.session_state.get('debug_mode', False):
                                logger.debug(f"Parse error: {str(parse_error)}")
                            return {
                                "success": False, 
                                "error": f"Failed to parse downloaded file: {str(parse_error)}",
                                "api_response": result
                            }
                    else:
                        # S3 download failed, try direct HTTP download as fallback
                        st.warning("⚠️ S3 download failed, trying direct HTTP download...")
                        logger.warning(f"S3 download failed: {download_result['error']}")
                        logger.info("Attempting direct HTTP download...")
                        
                        try:
                            # Try direct HTTP request to the S3 URL
                            response = requests.get(s3_url, timeout=60)
                            if response.status_code == 200:
                                file_content = response.content
                                filename = s3_url.split('/')[-1]
                                
                                st.success(f"βœ… Downloaded via HTTP: {filename}")
                                
                                # Parse the file content
                                if filename.lower().endswith('.csv'):
                                    df = pd.read_csv(io.BytesIO(file_content))
                                elif filename.lower().endswith(('.xlsx', '.xls')):
                                    df = pd.read_excel(io.BytesIO(file_content))
                                elif filename.lower().endswith('.json'):
                                    df = pd.read_json(io.BytesIO(file_content))
                                else:
                                    # Try CSV as default
                                    df = pd.read_csv(io.BytesIO(file_content))
                                
                                # Convert DataFrame to list of dictionaries
                                data_records = df.to_dict('records')
                                
                                st.info(f"πŸ“Š Parsed {len(data_records)} records from downloaded file")
                                
                                return {
                                    "data": data_records,
                                    "dataframe": df,
                                    "success": True,
                                    "records_count": len(data_records),
                                    "api_response": result,
                                    "s3_url": s3_url,
                                    "filename": filename,
                                    "file_content": file_content,
                                    "format": "tabular"
                                }
                            else:
                                st.error(f"❌ HTTP download failed with status {response.status_code}")
                                logger.error(f"HTTP download failed: {response.status_code}")
                                return {
                                    "success": False, 
                                    "error": f"Both S3 and HTTP download failed. S3 error: {download_result['error']}, HTTP status: {response.status_code}",
                                    "api_response": result
                                }
                        except Exception as http_error:
                            st.error(f"❌ Direct download failed: {str(http_error)}")
                            logger.error(f"HTTP download error: {str(http_error)}")
                            return {
                                "success": False, 
                                "error": f"Both S3 and HTTP download failed. S3 error: {download_result['error']}, HTTP error: {str(http_error)}",
                                "api_response": result
                            }
                else:
                    # No S3 URL found, check if data is directly in response
                    # Check both the main result and nested data object
                    data_obj = result.get("data", result)
                    
                    # Look for data in both locations
                    direct_data = None
                    if "data" in result and isinstance(result["data"], list):
                        direct_data = result["data"]
                    elif "data" in data_obj and isinstance(data_obj["data"], list):
                        direct_data = data_obj["data"]
                    elif isinstance(data_obj, list):
                        direct_data = data_obj
                    
                    if direct_data and len(direct_data) > 0:
                        st.info("πŸ“Š Using data directly from API response")
                        return {
                            "data": direct_data,
                            "success": True,
                            "records_count": len(direct_data),
                            "api_response": result,
                            "format": "tabular"
                        }
                    else:
                        st.warning("⚠️ No file URL or data found in API response")
                        return {
                            "success": False,
                            "error": "No file URL or data found in API response",
                            "api_response": result
                        }
                        
            except json.JSONDecodeError as e:
                st.error(f"❌ Failed to parse JSON response: {str(e)}")
                return {
                    "success": False, 
                    "error": f"Invalid JSON response: {str(e)}",
                    "raw_response": response.text
                }
                
        elif response.status_code == 401:
            st.error("❌ Authentication failed - Invalid API key")
            return {
                "success": False, 
                "error": "Invalid API key. Please check your credentials.",
                "status_code": 401,
                "response_text": response.text
            }
        elif response.status_code == 400:
            st.error(f"❌ Bad request - Check your input data")
            return {
                "success": False, 
                "error": f"Bad request: {response.text}",
                "status_code": 400,
                "response_text": response.text
            }
        else:
            st.error(f"❌ API error {response.status_code}")
            return {
                "success": False, 
                "error": f"API error {response.status_code}: {response.text}",
                "status_code": response.status_code,
                "response_text": response.text
            }
            
    except requests.exceptions.Timeout:
        st.error(f"❌ Request timed out after {API_TIMEOUT} seconds")
        return {"success": False, "error": f"Request timed out after {API_TIMEOUT} seconds"}
    except requests.exceptions.ConnectionError:
        st.error("❌ Could not connect to API server")
        return {"success": False, "error": "Could not connect to API server. Check your internet connection."}
    except Exception as e:
        st.error(f"❌ Unexpected error: {str(e)}")
        return {"success": False, "error": f"Unexpected error: {str(e)}"}


def render_generation_and_results(file_link, config, enabled=True):
    """Render generation button and results display"""
    if enabled:
        st.markdown('<h3 class="section-title step-incomplete">πŸš€ Step 4: Generate Data</h3>', unsafe_allow_html=True)
    else:
        st.markdown('<h3 class="section-title step-disabled">πŸš€ Step 4: Generate Data πŸ”’</h3>', unsafe_allow_html=True)
    
    if not enabled:
        st.info("πŸ”’ Complete Steps 1-3 to enable data generation")
        
        st.button(
            "πŸš€ Generate Data",
            use_container_width=True,
            type="primary",
            disabled=True
        )
        
        # Show placeholder results area
        st.markdown("**Results will appear here after generation**")
        st.empty()
        return
    
    
    # Generation button
    generate_clicked = st.button(
        f"πŸš€ Generate {st.session_state.output_format.upper()} Data",
        use_container_width=True,
        type="primary",
        help="Generate synthetic data using your uploaded file and configuration"
    )
    
    # Add timeout info
    st.info("⏱️ Data generation may take up to 30 minutes depending on file size and complexity. Please be patient!")
    
    # Handle generation
    if generate_clicked:
        # Show initial progress
        progress_placeholder, status_placeholder = render_generation_progress()
        
        # Get validated API key
        api_key = st.session_state.get('validated_api_key', '')
        
        # Update status
        with status_placeholder:
            st.info("πŸ” Preparing API request...")
        
        # Get file metadata from session state
        file_metadata = None
        # Look for file metadata in session state
        for key in st.session_state.keys():
            if isinstance(key, str) and key.startswith('file_metadata_'):
                file_metadata = st.session_state[key]
                break
        
        # Update status
        with status_placeholder:
            st.info("πŸ“‘ Sending request to generation API...")
        
        # Call API with file link, configuration, and file metadata
        result = call_generation_api(file_link, config, api_key, file_metadata, progress_placeholder, status_placeholder)
        
        # If API call failed with 403/401 and we have a presigned URL, try with that
        if (not result.get("success", False) and 
            result.get("status_code") in [401, 403] and
            "file_url" in st.session_state):
            
            # Look for presigned URL in session state
            presigned_key = f"{st.session_state.get('current_file_key', 'file_url')}_presigned"
            if presigned_key in st.session_state:
                presigned_url = st.session_state[presigned_key]
                st.info("πŸ”„ Retrying with authenticated URL...")
                logger.info("Retrying API call with presigned URL")
                
                # Retry with presigned URL
                result = call_generation_api(presigned_url, config, api_key, file_metadata, progress_placeholder, status_placeholder)
        
        # Handle API response
        if result.get("success", False):
            st.session_state.generated_data = result
            st.success("βœ… Data generation completed successfully!")
            
            # Display results
            render_results_display(result, result.get("records_count", config.get("num_rows", 100)))
            
            # Show metrics
            render_generation_metrics(result)
        else:
            # Clear progress indicators on error
            if progress_placeholder:
                with progress_placeholder:
                    pass  # Clear the placeholder
            if status_placeholder:
                with status_placeholder:
                    pass  # Clear the placeholder
            
            # Handle API errors
            error_message = result.get("error", "Unknown error occurred")
            st.error(f"❌ Generation failed: {error_message}")
            
            # Print detailed error information to console
            logger.error(f"Generation API error: {error_message}")
            
            # Log additional context for debugging
            if "status_code" in result:
                logger.error(f"Status Code: {result['status_code']}")
            if "api_response" in result and isinstance(result["api_response"], dict):
                logger.debug(f"API Response Keys: {list(result['api_response'].keys())}")
            
            # Show minimal error info in UI with option to see more
            with st.expander("πŸ” Error Details", expanded=False):
                st.markdown("**Summary:**")
                st.text(error_message)
                
                if "status_code" in result:
                    st.markdown(f"**Status Code:** {result['status_code']}")
                
                st.markdown("*Enable Debug Mode in sidebar for detailed console logs*")
    
    # Show previous results if they exist
    elif st.session_state.get('generated_data') and st.session_state.generated_data.get("success", False):
        st.markdown("**Previous Generation Results:**")
        render_results_display(st.session_state.generated_data, st.session_state.generated_data.get("records_count", config.get("num_rows", 100)))
        render_generation_metrics(st.session_state.generated_data)