Spaces:
Runtime error

File size: 28,292 Bytes
e6be672
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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/>.

"""
Select intent plugin — selects and highlights BIM elements for 3D visualization.

Returns element IDs and GUIDs that the viewer can use to highlight matching
elements by type, property, condition, spatial location, material, size range,
or compliance status.
"""

import logging
from typing import Dict, List, Any, Optional
from datetime import datetime
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, and_, or_, func

from app.models import Project, Element
from app.schemas.intent import (
    SingleQueryPlan, SingleQueryResult, MainIntent,
    PresentationFormat,
)
from app.core.intent_system.base_plugin import BaseIntentPlugin
from app.core.intent_system.decorators import sub_intent
from app.services.element_cache_service import element_cache_service

logger = logging.getLogger(__name__)


class SelectIntentPlugin(BaseIntentPlugin):
    """Plugin for the SELECT intent — returns element IDs for visualization."""

    def __init__(self):
        super().__init__()
        self.intent_type = MainIntent.SELECT
        self.supported_sub_intents = [
            "by_type",
            "by_property",
            "by_condition",
            "by_spatial_location",
            "by_material",
            "by_size_range",
            "by_compliance_status",
            "by_completeness",
            "by_assembly",
            "outliers",
        ]

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

    @sub_intent("select.by_type")
    async def handle_by_type(
        self,
        query_plan: SingleQueryPlan,
        project: Project,
        session: AsyncSession,
        context: Optional[Dict] = None,
    ) -> SingleQueryResult:
        """Select elements by IFC type for visualization — optimized with caching."""

        # Use optimized cached element selection service
        element_tuples = await element_cache_service.get_or_compute_element_ids(
            session=session,
            project_id=project.id,
            filter_groups=query_plan.filter_groups,
            use_cache=True,
            limit=1000,  # Reasonable limit for visualization
        )

        # Extract IDs and GUIDs
        element_ids = [str(elem_tuple[0]) for elem_tuple in element_tuples]
        element_guids = [
            elem_tuple[1] for elem_tuple in element_tuples if elem_tuple[1]
        ]

        count = len(element_tuples)

        # Get IFC type from filters
        ifc_type = query_plan.filter_groups.get("ifc_type", "elements")
        element_type_name = self._get_element_type_name(ifc_type)

        return self.create_result(
            query_plan=query_plan,
            result_text=f"Selected {count} {element_type_name} for visualization",
            explanation=(
                f"Found {count} elements of type {element_type_name} to highlight "
                f"in the 3D viewer using optimized cache-aware query"
            ),
            provenance=element_ids[:20],  # Limit provenance for performance
            result_data={
                "element_ids": element_ids,
                "element_guids": element_guids,
                "count": count,
                "selection_type": "by_type",
                "ifc_type": ifc_type,
                "element_type_name": element_type_name,
                "cache_optimized": True,
            },
            processing_steps=[
                "optimized_id_query",
                "cache_lookup",
                "element_selection",
            ],
            elements_processed=count,
        )

    @sub_intent("select.by_property")
    async def handle_by_property(
        self,
        query_plan: SingleQueryPlan,
        project: Project,
        session: AsyncSession,
        context: Optional[Dict] = None,
    ) -> SingleQueryResult:
        """Select elements by specific properties."""
        query = await self.build_base_query(
            session=session,
            project=project,
            filter_groups=query_plan.filter_groups,
            scope=query_plan.scope,
        )

        # Get elements with common properties for better response synthesis
        result = await session.execute(query)
        elements = result.scalars().all()

        # Extract IDs and build detailed result with properties
        element_ids = [str(elem.id) for elem in elements]
        element_guids = [
            elem.ifc_global_id for elem in elements if elem.ifc_global_id
        ]
        count = len(elements)

        # Build detailed element data with properties
        elements_data = []
        for elem in elements[:100]:  # Limit to 100 for performance
            elem_data = {
                "id": elem.ifc_global_id or str(elem.id),
                "name": elem.name,
                "type": elem.ifc_type,
            }

            # Add geometric properties if available
            if elem.height:
                elem_data["height_m"] = round(elem.height, 2)
            if elem.width:
                elem_data["width_m"] = round(elem.width, 2)
            if elem.length:
                elem_data["length_m"] = round(elem.length, 2)
            if elem.area:
                elem_data["area_m2"] = round(elem.area, 2)
            if elem.volume:
                elem_data["volume_m3"] = round(elem.volume, 3)
            if elem.level_name:
                elem_data["level"] = elem.level_name

            elements_data.append(elem_data)

        # Generate descriptive text based on filters
        filter_desc = self._describe_filters(query_plan.filter_groups)

        return self.create_result(
            query_plan=query_plan,
            result_text=f"Selected {count} elements with properties: {filter_desc}",
            explanation=f"Found {count} elements matching the specified property criteria",
            provenance=element_ids[:20],
            result_data={
                "elements": elements_data,
                "element_ids": element_ids,
                "element_guids": element_guids,
                "count": count,
                "selection_type": "by_property",
                "filters": query_plan.filter_groups,
                "showing": len(elements_data),
            },
            elements_processed=count,
        )

    @sub_intent("select.by_condition")
    async def handle_by_condition(
        self,
        query_plan: SingleQueryPlan,
        project: Project,
        session: AsyncSession,
        context: Optional[Dict] = None,
    ) -> SingleQueryResult:
        """Select elements meeting specific conditions (e.g., area < 1m2)."""
        query = await self.build_base_query(
            session=session,
            project=project,
            filter_groups=query_plan.filter_groups,
            scope=query_plan.scope,
        )

        # Get element IDs with relevant data for condition description
        query = query.with_only_columns(
            Element.id, Element.ifc_global_id, Element.ifc_type, Element.area
        )

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

        # Extract IDs
        element_ids = [str(elem.id) for elem in elements]
        element_guids = [
            elem.ifc_global_id for elem in elements if elem.ifc_global_id
        ]
        count = len(elements)

        # Build condition description
        condition_desc = self._describe_conditions(query_plan.filter_groups)
        ifc_type = query_plan.filter_groups.get("ifc_type", "elements")

        return self.create_result(
            query_plan=query_plan,
            result_text=f"Selected {count} {ifc_type} meeting condition: {condition_desc}",
            explanation=f"Found {count} elements that satisfy the specified conditions",
            provenance=element_ids,
            result_data={
                "element_ids": element_ids,
                "element_guids": element_guids,
                "count": count,
                "selection_type": "by_condition",
                "condition": condition_desc,
                "filters": query_plan.filter_groups,
            },
            elements_processed=count,
        )

    @sub_intent("select.by_spatial_location")
    async def handle_by_spatial_location(
        self,
        query_plan: SingleQueryPlan,
        project: Project,
        session: AsyncSession,
        context: Optional[Dict] = None,
    ) -> SingleQueryResult:
        """Select elements in specific spatial locations."""
        query = await self.build_base_query(
            session=session,
            project=project,
            filter_groups=query_plan.filter_groups,
            scope=query_plan.scope,
        )

        # Get element IDs
        query = query.with_only_columns(
            Element.id, Element.ifc_global_id, Element.level_name
        )

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

        element_ids = [str(elem.id) for elem in elements]
        element_guids = [
            elem.ifc_global_id for elem in elements if elem.ifc_global_id
        ]
        count = len(elements)

        # Get spatial context
        spatial_desc = query_plan.filter_groups.get(
            "building_story", "specified location"
        )

        return self.create_result(
            query_plan=query_plan,
            result_text=f"Selected {count} elements in {spatial_desc}",
            explanation=f"Found {count} elements in the specified spatial location",
            provenance=element_ids,
            result_data={
                "element_ids": element_ids,
                "element_guids": element_guids,
                "count": count,
                "selection_type": "by_spatial_location",
                "location": spatial_desc,
            },
            elements_processed=count,
        )

    @sub_intent("select.by_material")
    async def handle_by_material(
        self,
        query_plan: SingleQueryPlan,
        project: Project,
        session: AsyncSession,
        context: Optional[Dict] = None,
    ) -> SingleQueryResult:
        """Select elements by material type."""
        query = await self.build_base_query(
            session=session,
            project=project,
            filter_groups=query_plan.filter_groups,
            scope=query_plan.scope,
        )

        # Get element IDs
        query = query.with_only_columns(
            Element.id, Element.ifc_global_id, Element.material_name
        )

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

        element_ids = [str(elem.id) for elem in elements]
        element_guids = [
            elem.ifc_global_id for elem in elements if elem.ifc_global_id
        ]
        count = len(elements)

        # Get material info
        material = query_plan.filter_groups.get("material", "specified material")

        return self.create_result(
            query_plan=query_plan,
            result_text=f"Selected {count} elements with material: {material}",
            explanation=f"Found {count} elements made of {material}",
            provenance=element_ids,
            result_data={
                "element_ids": element_ids,
                "element_guids": element_guids,
                "count": count,
                "selection_type": "by_material",
                "material": material,
            },
            elements_processed=count,
        )

    @sub_intent("select.by_size_range")
    async def handle_by_size_range(
        self,
        query_plan: SingleQueryPlan,
        project: Project,
        session: AsyncSession,
        context: Optional[Dict] = None,
    ) -> SingleQueryResult:
        """Select elements within specific size ranges."""
        query = await self.build_base_query(
            session=session,
            project=project,
            filter_groups=query_plan.filter_groups,
            scope=query_plan.scope,
        )

        # Get element IDs
        query = query.with_only_columns(
            Element.id, Element.ifc_global_id, Element.area, Element.volume
        )

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

        element_ids = [str(elem.id) for elem in elements]
        element_guids = [
            elem.ifc_global_id for elem in elements if elem.ifc_global_id
        ]
        count = len(elements)

        # Describe size range
        size_desc = self._describe_size_range(query_plan.filter_groups)

        return self.create_result(
            query_plan=query_plan,
            result_text=f"Selected {count} elements within size range: {size_desc}",
            explanation=f"Found {count} elements matching the specified size criteria",
            provenance=element_ids,
            result_data={
                "element_ids": element_ids,
                "element_guids": element_guids,
                "count": count,
                "selection_type": "by_size_range",
                "size_criteria": size_desc,
            },
            elements_processed=count,
        )

    @sub_intent("select.by_compliance_status")
    async def handle_by_compliance_status(
        self,
        query_plan: SingleQueryPlan,
        project: Project,
        session: AsyncSession,
        context: Optional[Dict] = None,
    ) -> SingleQueryResult:
        """Select elements based on compliance status."""
        query = await self.build_base_query(
            session=session,
            project=project,
            filter_groups=query_plan.filter_groups,
            scope=query_plan.scope,
        )

        # Get element IDs
        query = query.with_only_columns(
            Element.id, Element.ifc_global_id, Element.fire_rating
        )

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

        element_ids = [str(elem.id) for elem in elements]
        element_guids = [
            elem.ifc_global_id for elem in elements if elem.ifc_global_id
        ]
        count = len(elements)

        # Describe compliance status
        compliance_desc = query_plan.filter_groups.get(
            "compliance_status", "specified compliance criteria"
        )

        return self.create_result(
            query_plan=query_plan,
            result_text=f"Selected {count} elements based on compliance: {compliance_desc}",
            explanation=f"Found {count} elements matching compliance criteria",
            provenance=element_ids,
            result_data={
                "element_ids": element_ids,
                "element_guids": element_guids,
                "count": count,
                "selection_type": "by_compliance_status",
                "compliance_criteria": compliance_desc,
            },
            elements_processed=count,
        )

    # ------------------------------------------------------------------
    # Private helper methods
    # ------------------------------------------------------------------

    def _describe_filters(self, filters: Dict[str, Any]) -> str:
        """Generate human-readable description of filters."""
        descriptions = []

        if "ifc_type" in filters:
            descriptions.append(f"type={filters['ifc_type']}")
        if "building_story" in filters:
            descriptions.append(f"floor={filters['building_story']}")
        if "material" in filters:
            descriptions.append(f"material={filters['material']}")
        if "is_external" in filters:
            descriptions.append(f"external={filters['is_external']}")
        if "is_load_bearing" in filters:
            descriptions.append(f"load-bearing={filters['is_load_bearing']}")

        return ", ".join(descriptions) if descriptions else "specified criteria"

    def _describe_conditions(self, filters: Dict[str, Any]) -> str:
        """Generate human-readable description of conditions."""
        conditions = []

        for field in ["area", "volume", "height", "width", "length"]:
            if field in filters:
                field_filter = filters[field]
                if isinstance(field_filter, dict):
                    if "$lt" in field_filter:
                        conditions.append(f"{field} < {field_filter['$lt']}")
                    elif "$lte" in field_filter:
                        conditions.append(f"{field} \u2264 {field_filter['$lte']}")
                    elif "$gt" in field_filter:
                        conditions.append(f"{field} > {field_filter['$gt']}")
                    elif "$gte" in field_filter:
                        conditions.append(f"{field} \u2265 {field_filter['$gte']}")

        return " and ".join(conditions) if conditions else "specified conditions"

    def _describe_size_range(self, filters: Dict[str, Any]) -> str:
        """Generate human-readable description of size range."""
        descriptions = []

        if "area" in filters:
            area_filter = filters["area"]
            if isinstance(area_filter, dict):
                if "$lt" in area_filter:
                    descriptions.append(f"area < {area_filter['$lt']}m\u00b2")
                elif "$gt" in area_filter:
                    descriptions.append(f"area > {area_filter['$gt']}m\u00b2")

        if "volume" in filters:
            vol_filter = filters["volume"]
            if isinstance(vol_filter, dict):
                if "$lt" in vol_filter:
                    descriptions.append(f"volume < {vol_filter['$lt']}m\u00b3")
                elif "$gt" in vol_filter:
                    descriptions.append(f"volume > {vol_filter['$gt']}m\u00b3")

        return ", ".join(descriptions) if descriptions else "specified size range"

    # ------------------------------------------------------------------
    # New sub-intents: completeness, assembly, outliers
    # ------------------------------------------------------------------

    @sub_intent("select.by_completeness")
    async def handle_by_completeness(
        self,
        query_plan: SingleQueryPlan,
        project: Project,
        session: AsyncSession,
        context: Optional[Dict] = None,
    ) -> SingleQueryResult:
        """Select elements by data completeness status for viewer highlighting."""
        logger.info(f"Selecting elements by completeness for project {project.id}")

        fragment = (query_plan.query_fragment or "").lower()

        # Determine completeness filter
        if any(w in fragment for w in ["complet", "tutti i dati", "all data"]):
            condition = and_(
                Element.has_geometry == True,
                Element.has_properties == True,
                Element.has_materials == True,
            )
            desc = "complete elements (geometry + properties + materials)"
        elif any(w in fragment for w in ["geometr", "geometry"]):
            if any(w in fragment for w in ["senza", "without", "missing", "no "]):
                condition = Element.has_geometry == False
                desc = "elements without geometry"
            else:
                condition = Element.has_geometry == True
                desc = "elements with geometry"
        elif any(w in fragment for w in ["material", "materiali"]):
            if any(w in fragment for w in ["senza", "without", "missing", "no "]):
                condition = Element.has_materials == False
                desc = "elements without materials"
            else:
                condition = Element.has_materials == True
                desc = "elements with materials"
        elif any(w in fragment for w in ["propriet", "propert"]):
            if any(w in fragment for w in ["senza", "without", "missing", "no "]):
                condition = Element.has_properties == False
                desc = "elements without properties"
            else:
                condition = Element.has_properties == True
                desc = "elements with properties"
        else:
            # Default: select incomplete elements
            condition = or_(
                Element.has_geometry == False,
                Element.has_properties == False,
                Element.has_materials == False,
            )
            desc = "incomplete elements"

        query = (
            select(Element.id, Element.ifc_global_id, Element.name, Element.ifc_type)
            .where(and_(Element.project_id == project.id, condition))
            .order_by(Element.ifc_type, Element.name)
            .limit(500)
        )

        result = await session.execute(query)
        rows = result.all()

        element_ids = [r.ifc_global_id for r in rows]

        return self.create_result(
            query_plan=query_plan,
            result_text=f"Selected {len(rows)} {desc}",
            confidence=0.95,
            explanation=f"Filtered by completeness flags: {desc}",
            provenance=element_ids[:20],
            result_data={
                "selected_ids": element_ids,
                "count": len(rows),
                "description": desc,
            },
            processing_steps=["completeness_filter", "id_extraction"],
            elements_processed=len(rows),
        )

    @sub_intent("select.by_assembly")
    async def handle_by_assembly(
        self,
        query_plan: SingleQueryPlan,
        project: Project,
        session: AsyncSession,
        context: Optional[Dict] = None,
    ) -> SingleQueryResult:
        """Select elements belonging to an assembly or parent for viewer highlighting."""
        logger.info(f"Selecting elements by assembly for project {project.id}")

        # Check for assembly_id or parent_element_id in filters
        assembly_id = self._get_filter_value(query_plan.filter_groups, "assembly_id")
        parent_id = self._get_filter_value(query_plan.filter_groups, "parent_element_id")

        if assembly_id:
            condition = Element.assembly_id == assembly_id
            desc = f"assembly {assembly_id}"
        elif parent_id:
            condition = Element.parent_element_id == parent_id
            desc = f"children of element {parent_id}"
        else:
            # Select all elements that belong to any assembly
            condition = Element.assembly_id.is_not(None)
            desc = "all assembled elements"

        query = (
            select(Element.id, Element.ifc_global_id, Element.name, Element.ifc_type)
            .where(and_(Element.project_id == project.id, condition))
            .order_by(Element.ifc_type, Element.name)
            .limit(500)
        )

        result = await session.execute(query)
        rows = result.all()

        element_ids = [r.ifc_global_id for r in rows]

        return self.create_result(
            query_plan=query_plan,
            result_text=f"Selected {len(rows)} elements ({desc})",
            confidence=0.95,
            explanation=f"Assembly-based selection: {desc}",
            provenance=element_ids[:20],
            result_data={
                "selected_ids": element_ids,
                "count": len(rows),
                "description": desc,
            },
            processing_steps=["assembly_filter", "id_extraction"],
            elements_processed=len(rows),
        )

    @sub_intent("select.outliers")
    async def handle_outliers(
        self,
        query_plan: SingleQueryPlan,
        project: Project,
        session: AsyncSession,
        context: Optional[Dict] = None,
    ) -> SingleQueryResult:
        """Select elements with anomalous dimensions (beyond 2 standard deviations)."""
        logger.info(f"Selecting outlier elements for project {project.id}")

        # Detect which field to check — default to area
        fragment = (query_plan.query_fragment or "").lower()
        if any(w in fragment for w in ["volume", "volum"]):
            col = Element.volume
            field_name = "volume"
        elif any(w in fragment for w in ["height", "altezza", "alto", "alt"]):
            col = Element.height
            field_name = "height"
        elif any(w in fragment for w in ["length", "lunghezza", "lung"]):
            col = Element.length
            field_name = "length"
        elif any(w in fragment for w in ["width", "larghezza", "larg"]):
            col = Element.width
            field_name = "width"
        else:
            col = Element.area
            field_name = "area"

        unit = self.get_unit_for_field(field_name, project)

        # Calculate stats per ifc_type
        stats_query = (
            select(
                Element.ifc_type,
                func.avg(col).label("avg_val"),
                func.stddev(col).label("stddev_val"),
            )
            .where(and_(Element.project_id == project.id, col.is_not(None)))
            .group_by(Element.ifc_type)
            .having(func.stddev(col) > 0)
        )
        stats_result = await session.execute(stats_query)
        type_stats = {r.ifc_type: (float(r.avg_val), float(r.stddev_val)) for r in stats_result.all()}

        if not type_stats:
            return self.create_result(
                query_plan=query_plan,
                result_text=f"No outliers found — insufficient data for {field_name} analysis",
                confidence=0.9,
                explanation="Not enough data to compute standard deviation",
                result_data={"outliers": [], "field": field_name},
                provenance=[],
                processing_steps=["stats_calculation"],
            )

        # Find outliers: elements beyond ±2 stddev from their type's mean
        outlier_conditions = []
        for ifc_type, (avg, stddev) in type_stats.items():
            lower = avg - 2 * stddev
            upper = avg + 2 * stddev
            outlier_conditions.append(
                and_(
                    Element.ifc_type == ifc_type,
                    or_(col < lower, col > upper),
                )
            )

        query = (
            select(Element.id, Element.ifc_global_id, Element.name, Element.ifc_type, col.label("value"))
            .where(
                and_(
                    Element.project_id == project.id,
                    col.is_not(None),
                    or_(*outlier_conditions),
                )
            )
            .order_by(col.desc())
            .limit(500)
        )

        result = await session.execute(query)
        rows = result.all()

        element_ids = [r.ifc_global_id for r in rows]
        outlier_data = [
            {
                "id": r.ifc_global_id,
                "name": r.name,
                "type": r.ifc_type,
                "value": round(float(r.value), 2) if r.value else None,
                "unit": unit,
            }
            for r in rows[:50]
        ]

        return self.create_result(
            query_plan=query_plan,
            result_text=f"Found {len(rows)} outlier elements by {field_name} (±2σ from type mean)",
            confidence=0.90,
            explanation=f"Elements with {field_name} beyond 2 standard deviations from their type average",
            provenance=element_ids[:20],
            result_data={
                "selected_ids": element_ids,
                "count": len(rows),
                "field": field_name,
                "unit": unit,
                "outliers": outlier_data,
                "type_stats": {k: {"mean": round(v[0], 2), "stddev": round(v[1], 2)} for k, v in type_stats.items()},
            },
            processing_steps=["stats_per_type", "outlier_detection", "id_extraction"],
            elements_processed=len(rows),
        )