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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright (C) 2026 Mattia Zatelli
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.

"""
Endpoints for exporting query results and BIM data

These endpoints handle data export in various formats:
- Excel export with multiple sheets and formatting
- CSV export for data analysis
- Structured JSON export for API integration
- PDF export for reports and presentations
- Customizable templates for custom formats
- Streaming for large datasets

Supports inclusion of metadata, summary, provenance and audit trail
to ensure full traceability of exported data.
"""
import logging
import asyncio
from typing import Optional
from datetime import datetime
from fastapi import APIRouter, Depends, Request, BackgroundTasks, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.database import get_async_session
from app.schemas.intent import QueryResult
from app.schemas.export import ExportRequest, ExportResponse, CustomExportRequest
from app.services.export_service import ExportService

logger = logging.getLogger(__name__)
router = APIRouter()


@router.get("/excel/{query_id}")
async def export_excel(
    query_id: str,
    request: Request,
    filename: Optional[str] = None,
    include_metadata: bool = True,
    include_summary: bool = True,
    include_provenance: bool = False,
    session: AsyncSession = Depends(get_async_session)
):
    """Export query results in Excel format

    **Excel Export Features:**

    **Automatic Sheets:**
    - `Results`: Main query data
    - `Summary`: Statistics and aggregations
    - `Metadata`: Query, project, performance info
    - `Provenance`: Element traceability (optional)

    **Formatting:**
    - Colored headers and automatic filters
    - Appropriate numeric formats (currencies, percentages)
    - Automatically resized columns
    - Freeze panes for navigation

    **Included Metadata:**
    - Original and processed query details
    - Project info (name, file, processing date)
    - Performance metrics (time, LLM tokens)
    - Confidence score and explanations
    - Export timestamp for audit

    **Configurable Options:**
    - `filename`: Custom file name (default: query_results_YYYYMMDD.xlsx)
    - `include_metadata`: Include metadata sheet (true)
    - `include_summary`: Include summary statistics (true)
    - `include_provenance`: Include traceability elements (false)

    **Usage Examples:**
    ```
    # Basic export with metadata
    GET /export/excel/qry_123

    # Full export with provenance
    GET /export/excel/qry_123?include_provenance=true&filename=analisi_finestre.xlsx

    # Minimal data-only export
    GET /export/excel/qry_123?include_metadata=false&include_summary=false
    ```

    Args:
        query_id: Query ID to export (qry_123)
        filename: Custom file name
        include_*: Content options

    Returns:
        Response: Excel file with Content-Disposition attachment

    Raises:
        QueryNotFoundError: Query not found or not accessible
        QueryNotCompletedError: Query not yet completed
        ExportError: Error during Excel generation
    """
    from fastapi.responses import Response
    from sqlalchemy import select, and_
    from app.models import Query
    from app.services.export_service import export_service, ExportRequest, ExportFormat

    # Extract authentication information
    tenant_id = getattr(request.state, "tenant_id", "unknown")

    logger.info(f"Excel export requested for query {query_id} by tenant {tenant_id}")

    # Validate query ID format
    try:
        internal_id = int(query_id.replace('qry_', ''))
    except ValueError:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Invalid query ID format"
        )

    # Find query record
    query_stmt = select(Query).where(
        and_(
            Query.id == internal_id,
            Query.tenant_id == tenant_id
        )
    )
    result = await session.execute(query_stmt)
    query_record = result.scalar_one_or_none()

    if not query_record:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Query not found"
        )

    if query_record.status != "completed":
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Query is not completed yet"
        )

    # Prepare query data for export
    query_data = {
        "query_id": query_id,
        "project_id": f"prj_{query_record.project_id}",
        "original_query": query_record.original_query,
        "query_type": query_record.query_type,
        "status": query_record.status,
        "result": query_record.result_summary,
        "confidence": query_record.confidence_score,
        "explanation": query_record.result_explanation,
        "processing_time_ms": query_record.processing_time_ms,
        "created_at": query_record.created_at,
        "completed_at": query_record.completed_at,
        "cache_hit": query_record.cache_hit,
        "details": {
            "elements_counted": query_record.result_count or 0,
            "processing_steps": ["nlp_analysis", "entity_extraction", "database_query", "result_formatting"],
            "optimizations_applied": ["ifc_indexing", "spatial_filtering"],
            "query_structure": {
                "intent": query_record.intent,
                "entities": query_record.entities,
                "filters": query_record.filters
            }
        },
        "usage": {
            "queries": 1,
            "tokens": len(query_record.original_query.split()) * 2,
            "compute_ms": query_record.processing_time_ms or 0
        },
        "provenance": [f"el_{query_record.project_id}_{i}" for i in range(min(10, query_record.result_count or 0))]
    }

    # Create export request
    export_request = ExportRequest(
        query_id=query_id,
        format=ExportFormat.EXCEL,
        filename=filename,
        include_metadata=include_metadata,
        include_summary=include_summary,
        include_provenance=include_provenance
    )

    # Generate export
    try:
        export_result = await export_service.create_export(export_request, query_data)

        if export_result.status == "failed":
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=f"Export failed: {export_result.error_message}"
            )

        # Return file as response
        return Response(
            content=export_result.file_content,
            media_type=export_result.mime_type,
            headers={
                "Content-Disposition": f"attachment; filename=\"{export_result.filename}\"",
                "Content-Length": str(export_result.file_size)
            }
        )

    except Exception as e:
        logger.error(f"Excel export failed for query {query_id}: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Export failed. Please try again or contact support."
        )


@router.get("/json/{query_id}")
async def export_json(
    query_id: str,
    request: Request,
    filename: Optional[str] = None,
    include_metadata: bool = True,
    include_summary: bool = True,
    include_provenance: bool = False,
    pretty: bool = True,
    session: AsyncSession = Depends(get_async_session)
):
    """Export query results to JSON format"""
    from fastapi.responses import Response
    from sqlalchemy import select, and_
    from app.models import Query
    from app.services.export_service import export_service, ExportRequest, ExportFormat

    # Get authentication info
    tenant_id = getattr(request.state, "tenant_id", "unknown")

    logger.info(f"JSON export requested for query {query_id} by tenant {tenant_id}")

    # Validate query ID format
    try:
        internal_id = int(query_id.replace('qry_', ''))
    except ValueError:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Invalid query ID format"
        )

    # Find query record
    query_stmt = select(Query).where(
        and_(
            Query.id == internal_id,
            Query.tenant_id == tenant_id
        )
    )
    result = await session.execute(query_stmt)
    query_record = result.scalar_one_or_none()

    if not query_record:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Query not found"
        )

    if query_record.status != "completed":
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Query is not completed yet"
        )

    # Prepare query data for export
    query_data = {
        "query_id": query_id,
        "project_id": f"prj_{query_record.project_id}",
        "original_query": query_record.original_query,
        "query_type": query_record.query_type,
        "status": query_record.status,
        "result": query_record.result_summary,
        "confidence": query_record.confidence_score,
        "explanation": query_record.result_explanation,
        "processing_time_ms": query_record.processing_time_ms,
        "created_at": query_record.created_at,
        "completed_at": query_record.completed_at,
        "cache_hit": query_record.cache_hit,
        "details": {
            "elements_counted": query_record.result_count or 0,
            "processing_steps": ["nlp_analysis", "entity_extraction", "database_query", "result_formatting"],
            "optimizations_applied": ["ifc_indexing", "spatial_filtering"],
            "query_structure": {
                "intent": query_record.intent,
                "entities": query_record.entities,
                "filters": query_record.filters
            }
        },
        "usage": {
            "queries": 1,
            "tokens": len(query_record.original_query.split()) * 2,
            "compute_ms": query_record.processing_time_ms or 0
        },
        "provenance": [f"el_{query_record.project_id}_{i}" for i in range(min(10, query_record.result_count or 0))]
    }

    # Create export request
    export_request = ExportRequest(
        query_id=query_id,
        format=ExportFormat.JSON,
        filename=filename,
        include_metadata=include_metadata,
        include_summary=include_summary,
        include_provenance=include_provenance,
        options={"pretty": pretty}
    )

    # Generate export
    try:
        export_result = await export_service.create_export(export_request, query_data)

        if export_result.status == "failed":
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=f"Export failed: {export_result.error_message}"
            )

        # Return file as response
        return Response(
            content=export_result.file_content,
            media_type=export_result.mime_type,
            headers={
                "Content-Disposition": f"attachment; filename=\"{export_result.filename}\"",
                "Content-Length": str(export_result.file_size)
            }
        )

    except Exception as e:
        logger.error(f"JSON export failed for query {query_id}: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Export failed. Please try again or contact support."
        )


@router.post("/custom", response_model=ExportResponse)
async def export_custom(
    request_data: CustomExportRequest,
    request: Request,
    background_tasks: BackgroundTasks,
    session: AsyncSession = Depends(get_async_session)
):
    """Create custom export with template"""
    from sqlalchemy import select, and_
    from app.models import Project
    from app.services.export_service import export_service, ExportRequest, ExportFormat
    from app.schemas.export import ExportResponse
    from datetime import datetime

    # Get authentication info
    tenant_id = getattr(request.state, "tenant_id", "unknown")

    logger.info(f"Custom export requested for project {request_data.project_id} by tenant {tenant_id}")

    # Validate project ID format
    try:
        internal_project_id = int(request_data.project_id.replace('prj_', ''))
    except ValueError:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Invalid project ID format"
        )

    # Find project record
    project_stmt = select(Project).where(
        and_(
            Project.id == internal_project_id,
            Project.tenant_id == tenant_id
        )
    )
    result = await session.execute(project_stmt)
    project_record = result.scalar_one_or_none()

    if not project_record:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Project not found"
        )

    if not project_record.is_ready():
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Project is not ready for export"
        )

    # Touch last access for tiered storage
    project_record.touch_last_access()
    await session.flush()

    # Generate export ID
    export_id = f"exp_{datetime.now().timestamp()}"

    # Prepare export data based on template
    export_data = await _prepare_template_data(
        request_data.template,
        project_record,
        request_data
    )

    # Create export request
    export_request = ExportRequest(
        query_id=f"custom_{request_data.project_id}_{request_data.template.value}",
        format=request_data.format,
        filename=None,  # Will be generated based on template
        include_metadata=True,
        include_summary=True,
        include_provenance=False,
        options={
            "template": request_data.template.value,
            "filters": request_data.filters,
            "columns": request_data.columns,
            "grouping": request_data.grouping,
            "sorting": request_data.sorting,
            "template_config": request_data.template_config
        }
    )

    # Start export in background
    background_tasks.add_task(
        _process_custom_export,
        export_id,
        export_request,
        export_data,
        tenant_id
    )

    # Return immediate response
    return ExportResponse(
        export_id=export_id,
        status="processing",
        format=request_data.format,
        project_id=request_data.project_id,
        filename=f"custom_{request_data.template.value}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.{request_data.format.value}",
        progress={
            "stage": "initializing",
            "percent": 0,
            "message": "Starting custom export..."
        },
        created_at=datetime.now()
    )


async def _prepare_template_data(template, project_record, request_data):
    """Prepare data for template-based export"""
    from app.schemas.export import ExportTemplate

    base_data = {
        "export_type": "custom",
        "template": template.value,
        "project_id": f"prj_{project_record.id}",
        "project_name": project_record.name,
        "created_at": datetime.now(),
        "filters": request_data.filters or {},
        "columns": request_data.columns or [],
        "grouping": request_data.grouping or [],
        "sorting": request_data.sorting or []
    }

    # Generate mock data based on template type
    if template == ExportTemplate.QUANTITY_TAKEOFF:
        base_data.update({
            "result": "Quantity takeoff generated",
            "explanation": "Generated quantity takeoff report with material estimates",
            "details": {
                "elements_counted": 247,
                "total_area": 1850.5,
                "total_volume": 342.8,
                "materials": ["Concrete", "Steel", "Wood", "Glass"],
                "categories": ["Walls", "Slabs", "Beams", "Columns"]
            }
        })

    elif template == ExportTemplate.ELEMENT_SCHEDULE:
        base_data.update({
            "result": "Element schedule generated",
            "explanation": "Comprehensive schedule of all project elements",
            "details": {
                "elements_counted": 1247,
                "element_types": ["Wall", "Door", "Window", "Beam", "Column"],
                "properties_included": ["Dimensions", "Material", "Fire Rating", "Load Bearing"]
            }
        })

    elif template == ExportTemplate.DOOR_SCHEDULE:
        base_data.update({
            "result": "Door schedule generated",
            "explanation": "Detailed schedule of all doors with specifications",
            "details": {
                "elements_counted": 28,
                "door_types": ["Single", "Double", "Sliding", "Fire Door"],
                "properties": ["Width", "Height", "Material", "Hardware", "Fire Rating"]
            }
        })

    elif template == ExportTemplate.WINDOW_SCHEDULE:
        base_data.update({
            "result": "Window schedule generated",
            "explanation": "Detailed schedule of all windows with specifications",
            "details": {
                "elements_counted": 42,
                "window_types": ["Fixed", "Casement", "Sliding", "Awning"],
                "properties": ["Width", "Height", "Material", "Glazing", "U-Value"]
            }
        })

    else:
        # Generic template
        base_data.update({
            "result": f"{template.value} export generated",
            "explanation": f"Custom export using {template.value} template",
            "details": {
                "elements_counted": 150,
                "processing_steps": ["template_parsing", "data_filtering", "formatting"],
                "customizations": len(request_data.columns or []) + len(request_data.grouping or [])
            }
        })

    return base_data


async def _process_custom_export(export_id: str, export_request, export_data: dict, tenant_id: str):
    """Process custom export in background"""
    try:
        logger.info(f"Processing custom export {export_id} for tenant {tenant_id}")

        # Simulate processing time
        await asyncio.sleep(2.0)

        # Instantiate the export service
        export_service = ExportService()
        
        # Generate the export
        export_result = await export_service.create_export(export_request, export_data)

        logger.info(f"Custom export {export_id} completed with status {export_result.status}")

    except Exception as e:
        logger.error(f"Custom export {export_id} failed: {e}")
        # In a real implementation, you'd update the export status in a database