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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
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
# 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/>.

"""
Export intent plugin — CSV, XLSX, JSON, BCF, IFC, and PDF export.

Generates file exports in multiple formats for BIM element data,
including tabular formats (CSV/XLSX), structured data (JSON),
collaboration formats (BCF), native BIM formats (IFC), and reports (PDF).
"""

import logging
import csv
import io
import json
from typing import Dict, List, Any, Optional
from datetime import datetime

from sqlalchemy.ext.asyncio import AsyncSession

from app.models import Project, Element
from app.schemas.intent import SingleQueryPlan, SingleQueryResult, MainIntent
from app.core.intent_system.base_plugin import BaseIntentPlugin
from app.core.intent_system.decorators import sub_intent

logger = logging.getLogger(__name__)


class ExportIntentPlugin(BaseIntentPlugin):
    """Plugin for the EXPORT intent — CSV/XLSX/JSON/BCF/IFC/PDF export."""

    def __init__(self):
        super().__init__()
        self.intent_type = MainIntent.EXPORT
        self.supported_sub_intents = [
            "export.csv",
            "export.xlsx",
            "export.json",
            "export.bcf",
            "export.ifc",
            "export.pdf",
        ]

        # Default CSV columns for element export
        self.default_csv_columns = [
            "id", "ifc_global_id", "ifc_type", "name", "level_name",
            "area", "volume", "height", "width", "length",
            "material_name", "is_load_bearing", "is_external",
            "fire_rating", "thermal_transmittance",
        ]

    # ------------------------------------------------------------------
    # Sub-intent handlers
    # ------------------------------------------------------------------

    @sub_intent("export.csv")
    async def handle_export_csv(
        self,
        query_plan: SingleQueryPlan,
        project: Project,
        session: AsyncSession,
        context: Optional[Dict] = None,
    ) -> SingleQueryResult:
        """Export elements to CSV format."""
        logger.info(f"Exporting elements to CSV for project {project.id}")

        # Build query
        query = await self.build_base_query(
            session=session,
            project=project,
            filter_groups=query_plan.filter_groups,
            scope=query_plan.scope,
        )

        # Execute query
        result = await session.execute(query)
        elements = result.scalars().all()

        if not elements:
            return self.create_result(
                query_plan=query_plan,
                result_text="No elements to export",
                explanation="No elements match the specified criteria",
                result_data={"total_elements": 0},
                provenance=["database_query"],
            )

        # Generate CSV
        csv_data = self._generate_csv(elements)

        # Calculate file size
        file_size_bytes = len(csv_data.encode("utf-8"))
        file_size_kb = round(file_size_bytes / 1024, 2)

        return self.create_result(
            query_plan=query_plan,
            result_text=f"CSV export ready: {len(elements)} elements ({file_size_kb} KB)",
            explanation=(
                f"Generated CSV file with {len(elements)} elements "
                f"and {len(self.default_csv_columns)} columns"
            ),
            result_data={
                "format": "csv",
                "total_elements": len(elements),
                "columns": self.default_csv_columns,
                "file_size_bytes": file_size_bytes,
                "file_size_kb": file_size_kb,
                "csv_content": csv_data,
                "download_ready": True,
            },
            provenance=["database_query", "csv_generation"],
            elements_processed=len(elements),
        )

    @sub_intent("export.xlsx")
    async def handle_export_xlsx(
        self,
        query_plan: SingleQueryPlan,
        project: Project,
        session: AsyncSession,
        context: Optional[Dict] = None,
    ) -> SingleQueryResult:
        """Export elements to Excel (XLSX) format."""
        logger.info(f"Exporting elements to XLSX for project {project.id}")

        # Build query
        query = await self.build_base_query(
            session=session,
            project=project,
            filter_groups=query_plan.filter_groups,
            scope=query_plan.scope,
        )

        result = await session.execute(query)
        elements = result.scalars().all()

        if not elements:
            return self.create_result(
                query_plan=query_plan,
                result_text="No elements to export",
                explanation="No elements match the specified criteria",
                result_data={"total_elements": 0},
                provenance=["database_query"],
            )

        # Generate Excel metadata (actual file generation would require openpyxl)
        xlsx_metadata = self._prepare_xlsx_metadata(elements)

        return self.create_result(
            query_plan=query_plan,
            result_text=f"Excel export ready: {len(elements)} elements",
            explanation=(
                f"Prepared Excel workbook with {len(elements)} elements "
                f"across {xlsx_metadata['sheet_count']} sheets"
            ),
            result_data=xlsx_metadata,
            provenance=["database_query", "xlsx_preparation"],
            elements_processed=len(elements),
            limitations=[
                "Full XLSX generation requires openpyxl library installation",
            ],
        )

    @sub_intent("export.json")
    async def handle_export_json(
        self,
        query_plan: SingleQueryPlan,
        project: Project,
        session: AsyncSession,
        context: Optional[Dict] = None,
    ) -> SingleQueryResult:
        """Export elements to JSON format."""
        logger.info(f"Exporting elements to JSON for project {project.id}")

        # Build query
        query = await self.build_base_query(
            session=session,
            project=project,
            filter_groups=query_plan.filter_groups,
            scope=query_plan.scope,
        )

        result = await session.execute(query)
        elements = result.scalars().all()

        if not elements:
            return self.create_result(
                query_plan=query_plan,
                result_text="No elements to export",
                explanation="No elements match the specified criteria",
                result_data={"total_elements": 0},
                provenance=["database_query"],
            )

        # Generate JSON
        json_data = self._generate_json(elements)

        # Calculate file size
        file_size_bytes = len(json_data.encode("utf-8"))
        file_size_kb = round(file_size_bytes / 1024, 2)

        return self.create_result(
            query_plan=query_plan,
            result_text=f"JSON export ready: {len(elements)} elements ({file_size_kb} KB)",
            explanation=(
                f"Generated JSON with {len(elements)} elements "
                f"and full property data"
            ),
            result_data={
                "format": "json",
                "total_elements": len(elements),
                "file_size_bytes": file_size_bytes,
                "file_size_kb": file_size_kb,
                "json_content": json_data,
                "download_ready": True,
            },
            provenance=["database_query", "json_generation"],
            elements_processed=len(elements),
        )

    @sub_intent("export.bcf")
    async def handle_export_bcf(
        self,
        query_plan: SingleQueryPlan,
        project: Project,
        session: AsyncSession,
        context: Optional[Dict] = None,
    ) -> SingleQueryResult:
        """Export to BCF (BIM Collaboration Format) for issues."""
        logger.info(f"Exporting to BCF for project {project.id}")

        # Build query
        query = await self.build_base_query(
            session=session,
            project=project,
            filter_groups=query_plan.filter_groups,
            scope=query_plan.scope,
        )

        result = await session.execute(query)
        elements = result.scalars().all()

        if not elements:
            return self.create_result(
                query_plan=query_plan,
                result_text="No elements to export as BCF issues",
                explanation="No elements match the specified criteria",
                result_data={"total_elements": 0},
                provenance=["database_query"],
            )

        # Prepare BCF structure
        bcf_structure = self._prepare_bcf_structure(elements, project)

        return self.create_result(
            query_plan=query_plan,
            result_text=(
                f"BCF export prepared: {bcf_structure['topic_count']} topics "
                f"from {len(elements)} elements"
            ),
            explanation=(
                f"BCF 2.1 format with {bcf_structure['topic_count']} topics "
                f"ready for download"
            ),
            result_data=bcf_structure,
            provenance=["database_query", "bcf_preparation"],
            elements_processed=len(elements),
            limitations=["Full BCF ZIP generation requires bcf-xml library"],
        )

    @sub_intent("export.ifc")
    async def handle_export_ifc(
        self,
        query_plan: SingleQueryPlan,
        project: Project,
        session: AsyncSession,
        context: Optional[Dict] = None,
    ) -> SingleQueryResult:
        """Export filtered elements to IFC file."""
        logger.info(f"Exporting filtered IFC for project {project.id}")

        # Build query
        query = await self.build_base_query(
            session=session,
            project=project,
            filter_groups=query_plan.filter_groups,
            scope=query_plan.scope,
        )

        result = await session.execute(query)
        elements = result.scalars().all()

        if not elements:
            return self.create_result(
                query_plan=query_plan,
                result_text="No elements to export to IFC",
                explanation="No elements match the specified criteria",
                result_data={"total_elements": 0},
                provenance=["database_query"],
            )

        # Prepare IFC export metadata
        ifc_metadata = self._prepare_ifc_export(elements, project)

        return self.create_result(
            query_plan=query_plan,
            result_text=f"IFC export prepared: {len(elements)} elements",
            explanation=(
                f"Filtered IFC with {len(elements)} elements "
                f"from {ifc_metadata['total_types']} types"
            ),
            result_data=ifc_metadata,
            provenance=["database_query", "ifc_filter_preparation"],
            elements_processed=len(elements),
            limitations=[
                "Full IFC file generation requires ifcopenshell library "
                "and source IFC access",
            ],
        )

    @sub_intent("export.pdf")
    async def handle_export_pdf(
        self,
        query_plan: SingleQueryPlan,
        project: Project,
        session: AsyncSession,
        context: Optional[Dict] = None,
    ) -> SingleQueryResult:
        """Generate PDF report for elements."""
        logger.info(f"Generating PDF report for project {project.id}")

        # Build query
        query = await self.build_base_query(
            session=session,
            project=project,
            filter_groups=query_plan.filter_groups,
            scope=query_plan.scope,
        )

        result = await session.execute(query)
        elements = result.scalars().all()

        if not elements:
            return self.create_result(
                query_plan=query_plan,
                result_text="No elements for PDF report",
                explanation="No elements match the specified criteria",
                result_data={"total_elements": 0},
                provenance=["database_query"],
            )

        # Prepare PDF report structure
        pdf_structure = self._prepare_pdf_report(elements, project)

        return self.create_result(
            query_plan=query_plan,
            result_text=f"PDF report prepared: {len(elements)} elements",
            explanation=(
                f"PDF report with {pdf_structure['page_count']} pages "
                f"covering {len(elements)} elements"
            ),
            result_data=pdf_structure,
            provenance=["database_query", "pdf_preparation"],
            elements_processed=len(elements),
            limitations=["Full PDF generation requires reportlab library"],
        )

    # ------------------------------------------------------------------
    # Helper methods
    # ------------------------------------------------------------------

    def _generate_csv(self, elements: List[Element]) -> str:
        """Generate CSV content from elements."""
        output = io.StringIO()
        writer = csv.DictWriter(output, fieldnames=self.default_csv_columns)

        # Write header
        writer.writeheader()

        # Write rows
        for element in elements:
            row = {}
            for col in self.default_csv_columns:
                value = getattr(element, col, None)
                if value is None:
                    row[col] = ""
                elif isinstance(value, (int, float, bool)):
                    row[col] = str(value)
                else:
                    row[col] = str(value)
            writer.writerow(row)

        csv_content = output.getvalue()
        output.close()
        return csv_content

    def _prepare_xlsx_metadata(self, elements: List[Element]) -> Dict[str, Any]:
        """Prepare Excel workbook metadata."""
        # Group elements by type for multiple sheets
        by_type: Dict[str, list] = {}
        for element in elements:
            ifc_type = element.ifc_type
            if ifc_type not in by_type:
                by_type[ifc_type] = []
            by_type[ifc_type].append(element)

        sheets = []
        for ifc_type, type_elements in by_type.items():
            sheets.append(
                {
                    "name": ifc_type,
                    "row_count": len(type_elements),
                    "columns": self.default_csv_columns,
                }
            )

        return {
            "format": "xlsx",
            "total_elements": len(elements),
            "sheet_count": len(sheets),
            "sheets": sheets,
            "workbook_name": (
                f"elements_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
            ),
            "download_ready": False,
            "requires_library": "openpyxl",
        }

    def _generate_json(self, elements: List[Element]) -> str:
        """Generate JSON content from elements."""
        elements_data = []

        for element in elements:
            elem_dict = {
                "id": element.id,
                "ifc_global_id": element.ifc_global_id,
                "ifc_type": element.ifc_type,
                "name": element.name,
                "level_name": element.level_name,
                "measurements": {
                    "area": element.area,
                    "volume": element.volume,
                    "height": element.height,
                    "width": element.width,
                    "length": element.length,
                    "perimeter": element.perimeter,
                },
                "properties": element.properties if element.properties else {},
                "quantities": element.quantities if element.quantities else {},
                "material_name": element.material_name,
                "is_load_bearing": element.is_load_bearing,
                "is_external": element.is_external,
                "fire_rating": element.fire_rating,
                "thermal_transmittance": element.thermal_transmittance,
                "classifications": (
                    element.classifications if element.classifications else {}
                ),
            }
            elements_data.append(elem_dict)

        json_output = {
            "export_metadata": {
                "timestamp": datetime.now().isoformat(),
                "total_elements": len(elements),
                "format": "json",
            },
            "elements": elements_data,
        }

        return json.dumps(json_output, indent=2, ensure_ascii=False)

    def _prepare_bcf_structure(
        self, elements: List[Element], project: Project
    ) -> Dict[str, Any]:
        """Prepare BCF (BIM Collaboration Format) structure."""
        topics = []
        for element in elements[:50]:  # Limit to 50 topics for performance
            topic = {
                "guid": f"bcf-{element.ifc_global_id}",
                "title": f"Element: {element.name or element.ifc_type}",
                "description": (
                    f"Type: {element.ifc_type}, "
                    f"Level: {element.level_name or 'Unknown'}"
                ),
                "topic_type": "Info",
                "topic_status": "Open",
                "priority": "Normal",
                "assigned_to": None,
                "creation_date": datetime.now().isoformat(),
                "creation_author": "BIM Query",
                "labels": [element.ifc_type],
                "related_topics": [],
                "reference_links": [],
                "viewpoint": {
                    "guid": f"view-{element.ifc_global_id}",
                    "components": {
                        "selection": [element.ifc_global_id],
                    },
                },
            }
            topics.append(topic)

        return {
            "format": "bcf",
            "version": "2.1",
            "topic_count": len(topics),
            "topics": topics,
            "project_info": {
                "project_id": str(project.id),
                "project_name": project.name,
            },
            "markup_files": len(topics),
            "download_ready": False,
            "requires_library": "bcf-xml or custom BCF generation",
        }

    def _prepare_ifc_export(
        self, elements: List[Element], project: Project
    ) -> Dict[str, Any]:
        """Prepare IFC export metadata."""
        type_counts: Dict[str, int] = {}
        for element in elements:
            ifc_type = element.ifc_type
            type_counts[ifc_type] = type_counts.get(ifc_type, 0) + 1

        return {
            "format": "ifc",
            "schema": "IFC4",
            "total_elements": len(elements),
            "total_types": len(type_counts),
            "type_distribution": type_counts,
            "project_info": {
                "project_id": str(project.id),
                "project_name": project.name,
            },
            "element_guids": [e.ifc_global_id for e in elements[:100]],  # Sample
            "file_name": (
                f"filtered_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.ifc"
            ),
            "download_ready": False,
            "requires_library": "ifcopenshell and source IFC file access",
        }

    def _prepare_pdf_report(
        self, elements: List[Element], project: Project
    ) -> Dict[str, Any]:
        """Prepare PDF report structure."""
        elements_per_page = 10
        page_count = (len(elements) // elements_per_page) + (
            1 if len(elements) % elements_per_page > 0 else 0
        )
        page_count += 2  # Cover page + summary page

        # Group by type for summary
        by_type: Dict[str, int] = {}
        for element in elements:
            ifc_type = element.ifc_type
            by_type[ifc_type] = by_type.get(ifc_type, 0) + 1

        return {
            "format": "pdf",
            "total_elements": len(elements),
            "page_count": page_count,
            "sections": [
                {"name": "Cover Page", "page": 1},
                {
                    "name": "Summary",
                    "page": 2,
                    "content": {
                        "total_elements": len(elements),
                        "type_distribution": by_type,
                    },
                },
                {
                    "name": "Element Details",
                    "page_start": 3,
                    "page_end": page_count,
                    "elements_per_page": elements_per_page,
                },
            ],
            "project_info": {
                "project_id": str(project.id),
                "project_name": project.name,
                "export_date": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            },
            "file_name": (
                f"elements_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
            ),
            "download_ready": False,
            "requires_library": "reportlab",
        }