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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
# 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 BIM element management

These endpoints provide detailed access to processed BIM elements:
- Listing with advanced filters (type, material, geometry)
- Full-text search on properties and names
- Cursor-based pagination for performance
- Element aggregations and statistics
- Selective export for analysis

Supports complex combinable filters for specific analysis
and optimized queries for large datasets.
"""
import logging
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status, Request, Query as FastAPIQuery
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, and_, or_, func, desc

from app.core.database import get_async_session
from app.models import Project, Element, ProjectStatus
from app.schemas.element import (
    ElementResponse, ElementListResponse, ElementFilterRequest,
    ElementSummaryResponse
)
from app.schemas.common import ErrorResponse
from app.core.exceptions import ProjectNotFoundError, ProjectNotReadyError

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


async def get_project_for_elements(
    project_id: str,
    session: AsyncSession,
    tenant_id: str
) -> Project:
    """Retrieve and validate project for element operations

    Verifies that the project is accessible to the tenant, processed
    and ready for element listing/filtering operations.
    Updates access timestamp for tiered storage.

    Args:
        project_id: Project ID in external format (prj_123)
        session: Async database session
        tenant_id: Tenant ID for security isolation

    Returns:
        Project: Validated project with accessible elements

    Raises:
        ProjectNotFoundError: If project not found or not accessible
        ProjectNotReadyError: If project not yet processed
    """
    try:
        internal_id = int(project_id.replace('prj_', ''))
    except ValueError:
        raise ProjectNotFoundError(project_id)

    query = select(Project).where(
        and_(
            Project.id == internal_id,
            Project.tenant_id == tenant_id
        )
    )
    result = await session.execute(query)
    project = result.scalar_one_or_none()

    if not project:
        raise ProjectNotFoundError(project_id)

    if not project.is_ready():
        raise ProjectNotReadyError(project_id, project.status.value)

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

    return project


@router.get("/{project_id}/elements", response_model=ElementListResponse)
async def list_elements(
    project_id: str,
    request: Request,
    # === TYPE FILTERS ===
    ifc_type: Optional[List[str]] = FastAPIQuery(None, description="Filter by IFC types (IfcWall, IfcWindow, etc.)"),
    element_type: Optional[List[str]] = FastAPIQuery(None, description="Filter by element types (wall, window, door, etc.)"),
    level_name: Optional[List[str]] = FastAPIQuery(None, description="Filter by level/floor names"),
    material_name: Optional[str] = FastAPIQuery(None, description="Filter by material name (partial match)", max_length=200),

    # === NUMERIC FILTERS ===
    area_gt: Optional[float] = FastAPIQuery(None, description="Minimum area in m²"),
    area_lt: Optional[float] = FastAPIQuery(None, description="Maximum area in m²"),
    volume_gt: Optional[float] = FastAPIQuery(None, description="Minimum volume in m³"),
    volume_lt: Optional[float] = FastAPIQuery(None, description="Maximum volume in m³"),

    # === BOOLEAN FILTERS ===
    has_geometry: Optional[bool] = FastAPIQuery(None, description="Has 3D geometry"),
    has_properties: Optional[bool] = FastAPIQuery(None, description="Has IFC properties"),
    is_external: Optional[bool] = FastAPIQuery(None, description="Is external element"),

    # === SEARCH AND PAGINATION ===
    search: Optional[str] = FastAPIQuery(None, description="Full-text search on names and properties", max_length=200),
    limit: int = FastAPIQuery(50, description="Number of elements to return", ge=1, le=200),
    cursor: Optional[str] = FastAPIQuery(None, description="Pagination cursor for next elements"),

    session: AsyncSession = Depends(get_async_session)
):
    """
    List project elements with advanced filter options

    **Supported Filters:**

    **By Type:**
    - `ifc_type`: Standard IFC types (IfcWall, IfcWindow, IfcDoor, etc.)
    - `element_type`: Simplified types (wall, window, door, beam, column)
    - `level_name`: Filter by specific floor/level
    - `material_name`: Partial match search on material names

    **Numeric Filters:**
    - `area_gt/lt`: Surface area range in m²
    - `volume_gt/lt`: Volume range in m³
    - Supports combinations for precise ranges

    **Geometric Filters:**
    - `has_geometry`: Only elements with 3D representation
    - `has_properties`: Only elements with IFC properties
    - `is_external`: External envelope elements

    **Advanced Search:**
    - `search`: Full-text on names, descriptions and properties
    - Supports implicit AND operators for multiple words

    **Cursor-Based Pagination:**
    - More efficient for large datasets vs offset/limit
    - Consistent even with concurrent inserts/updates
    - `cursor` for forward/backward navigation

    **Usage Examples:**
    ```
    # All windows with area > 2m²
    GET /prj_123/elements?element_type=window&area_gt=2.0

    # External walls on ground floor
    GET /prj_123/elements?element_type=wall&is_external=true&level_name=Ground Floor

    # Search elements containing "acciaio"
    GET /prj_123/elements?search=acciaio

    # First 100 doors with geometry
    GET /prj_123/elements?element_type=door&has_geometry=true&limit=100
    ```

    Args:
        project_id: Project ID (prj_123)
        Various optional filter parameters

    Returns:
        ElementListResponse: Element list with pagination metadata

    Raises:
        ProjectNotFoundError: Project not found
        ProjectNotReadyError: Project not processed
        ValidationError: Invalid filter parameters
    """
    tenant_id = getattr(request.state, "tenant_id", "unknown")

    # === PROJECT VALIDATION ===
    project = await get_project_for_elements(project_id, session, tenant_id)

    # === BASE QUERY CONSTRUCTION ===
    # Optimized query with indexes on project_id and common filter fields
    query = select(Element).where(Element.project_id == project.id)

    # === APPLY FILTERS ===

    # Filter by IFC types (exact match, case insensitive)
    if ifc_type:
        query = query.where(Element.ifc_type.in_(ifc_type))

    # Filter by simplified element types
    if element_type:
        query = query.where(Element.element_type.in_(element_type))

    if level_name:
        query = query.where(Element.level_name.in_(level_name))

    if material_name:
        query = query.where(Element.material_name.ilike(f"%{material_name}%"))

    # Numeric filters
    if area_gt is not None:
        query = query.where(Element.area >= area_gt)
    if area_lt is not None:
        query = query.where(Element.area <= area_lt)
    if volume_gt is not None:
        query = query.where(Element.volume >= volume_gt)
    if volume_lt is not None:
        query = query.where(Element.volume <= volume_lt)

    # Boolean filters
    if has_geometry is not None:
        query = query.where(Element.has_geometry == has_geometry)
    if has_properties is not None:
        query = query.where(Element.has_properties == has_properties)
    if is_external is not None:
        query = query.where(Element.is_external == is_external)

    # Search filter
    if search:
        search_term = f"%{search.lower()}%"
        query = query.where(
            or_(
                Element.name.ilike(search_term),
                Element.description.ilike(search_term),
                Element.tag.ilike(search_term),
                Element.material_name.ilike(search_term)
            )
        )

    # Apply cursor pagination
    if cursor:
        try:
            cursor_id = int(cursor)
            query = query.where(Element.id > cursor_id)
        except ValueError:
            pass  # Invalid cursor, ignore

    # Apply limit and ordering
    query = query.order_by(Element.id).limit(limit + 1)

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

    # Check for more results
    has_next = len(elements) > limit
    if has_next:
        elements = elements[:-1]  # Remove extra element

    # Generate next cursor
    next_cursor = str(elements[-1].id) if has_next and elements else None

    # Convert to summary format
    element_summaries = []
    for element in elements:
        element_summaries.append({
            "element_id": f"el_{element.id}",
            "ifc_global_id": element.ifc_global_id,
            "ifc_type": element.ifc_type,
            "element_type": element.element_type,
            "name": element.name,
            "level_name": element.level_name,
            "area": element.area,
            "volume": element.volume,
            "material_name": element.material_name,
            "bounding_box": element.bounding_box,
            "centroid": {"x": element.centroid[0], "y": element.centroid[1], "z": element.centroid[2]} if element.centroid else None,
            "has_geometry": element.has_geometry,
            "has_properties": element.has_properties
        })

    # Get summary statistics for the filtered set
    count_query = select(func.count(Element.id)).where(Element.project_id == project.id)
    # Apply same filters to count query (simplified)
    if ifc_type:
        count_query = count_query.where(Element.ifc_type.in_(ifc_type))

    total_result = await session.execute(count_query)
    total_count = total_result.scalar()

    return ElementListResponse(
        elements=element_summaries,
        pagination={
            "limit": limit,
            "cursor": cursor,
            "has_next": has_next,
            "next_cursor": next_cursor,
            "total_count": total_count
        },
        total_elements=total_count,
        by_type=None,  # Could be expensive to calculate
        by_level=None
    )


@router.get("/{element_id}", response_model=ElementResponse)
async def get_element_details(
    element_id: str,
    request: Request,
    include_geometry: bool = FastAPIQuery(False, description="Include detailed geometry"),
    include_relationships: bool = FastAPIQuery(False, description="Include relationships"),
    session: AsyncSession = Depends(get_async_session)
):
    """
    Get detailed information about a specific element
    """
    tenant_id = getattr(request.state, "tenant_id", "unknown")

    # Parse element ID
    try:
        internal_id = int(element_id.replace('el_', ''))
    except ValueError:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Invalid element ID format"
        )

    # Query element with project info for tenant validation
    query = select(Element).join(Project).where(
        and_(
            Element.id == internal_id,
            Project.tenant_id == tenant_id
        )
    )
    result = await session.execute(query)
    element = result.scalar_one_or_none()

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

    # Touch last access for tiered storage (element access implies project access)
    project_query = select(Project).where(
        and_(
            Project.id == element.project_id,
            Project.tenant_id == tenant_id
        )
    )
    project_result = await session.execute(project_query)
    project = project_result.scalar_one_or_none()
    if project:
        project.touch_last_access()
        await session.flush()

    # Build response
    response_data = {
        "element_id": element_id,
        "project_id": f"prj_{element.project_id}",
        "ifc_global_id": element.ifc_global_id,
        "ifc_type": element.ifc_type,
        "ifc_class": element.ifc_class,
        "element_type": element.element_type,
        "name": element.name,
        "description": element.description,
        "tag": element.tag,
        "level_name": element.level_name,
        "level_elevation": element.level_elevation,
        "building_name": element.building_name,
        "site_name": element.site_name,

        # Metrics with units
        "area": {"value": element.area, "unit": "m2"} if element.area else None,
        "volume": {"value": element.volume, "unit": "m3"} if element.volume else None,
        "length": {"value": element.length, "unit": "m"} if element.length else None,
        "width": {"value": element.width, "unit": "m"} if element.width else None,
        "height": {"value": element.height, "unit": "m"} if element.height else None,
        "perimeter": {"value": element.perimeter, "unit": "m"} if element.perimeter else None,

        # Material
        "material_name": element.material_name,
        "material_category": element.material_category,
        "material_properties": element.material_properties or {},

        # Properties
        "properties": _format_properties(element.properties),
        "quantities": _format_quantities(element.quantities),
        "classifications": element.classifications or {},

        # Special properties
        "fire_rating": element.fire_rating,
        "acoustic_rating": element.acoustic_rating,
        "thermal_transmittance": element.thermal_transmittance,
        "thermal_mass": element.thermal_mass,

        # Flags
        "has_geometry": element.has_geometry,
        "has_properties": element.has_properties,
        "has_materials": element.has_materials,
        "is_external": element.is_external,
        "is_load_bearing": element.is_load_bearing,
        "combustible": element.combustible,

        # Timestamps
        "created_at": element.created_at,
        "updated_at": element.updated_at
    }

    # Add detailed geometry if requested
    if include_geometry and element.has_geometry:
        response_data["geometry"] = {
            "has_geometry": True,
            "bounding_box": element.bounding_box,
            "centroid": {"x": element.centroid[0], "y": element.centroid[1], "z": element.centroid[2]} if element.centroid else None,
            "surface_area": element.area,  # Placeholder
            "perimeter": element.perimeter,
            "lod": "medium"  # Placeholder
        }

    # Add relationships if requested
    if include_relationships:
        response_data["relationships"] = {
            "parent_element_id": f"el_{element.parent_element_id}" if element.parent_element_id else None,
            "child_element_ids": [],  # Would need additional query
            "adjacent_elements": [],  # Would need spatial analysis
            "containing_space": None,  # Would need spatial query
            "contained_elements": [],
            "assembly_id": element.assembly_id,
            "assembly_members": [],  # Would need additional query
            "connected_elements": [],
            "supports": [],
            "supported_by": []
        }

    return ElementResponse(**response_data)


def _format_properties(properties_dict: dict) -> dict:
    """Format properties dictionary for API response"""
    if not properties_dict:
        return {}

    formatted = {}
    for key, value in properties_dict.items():
        if isinstance(value, dict) and 'value' in value:
            # Already formatted
            formatted[key] = value
        else:
            # Simple value, format it
            formatted[key] = {
                "name": key,
                "value": value,
                "unit": None,
                "source": "IFC"
            }

    return formatted


def _format_quantities(quantities_dict: dict) -> dict:
    """Format quantities dictionary for API response"""
    if not quantities_dict:
        return {}

    formatted = {}
    for key, value in quantities_dict.items():
        if isinstance(value, dict):
            formatted[key] = value
        else:
            formatted[key] = {
                "value": value,
                "unit": "unknown"
            }

    return formatted


@router.get("/{project_id}/elements/summary", response_model=ElementSummaryResponse)
async def get_elements_summary(
    project_id: str,
    request: Request,
    session: AsyncSession = Depends(get_async_session)
):
    """
    Get summary statistics for all elements in a project
    """
    tenant_id = getattr(request.state, "tenant_id", "unknown")

    # Validate project
    project = await get_project_for_elements(project_id, session, tenant_id)

    # Get element counts by type
    type_query = select(
        Element.ifc_type,
        func.count(Element.id).label('count')
    ).where(
        Element.project_id == project.id
    ).group_by(Element.ifc_type)

    type_result = await session.execute(type_query)
    by_ifc_type = {row.ifc_type: row.count for row in type_result}

    # Get element counts by level
    level_query = select(
        Element.level_name,
        func.count(Element.id).label('count')
    ).where(
        and_(
            Element.project_id == project.id,
            Element.level_name.isnot(None)
        )
    ).group_by(Element.level_name)

    level_result = await session.execute(level_query)
    by_level = {row.level_name: row.count for row in level_result}

    # Get material counts
    material_query = select(
        Element.material_name,
        func.count(Element.id).label('count')
    ).where(
        and_(
            Element.project_id == project.id,
            Element.material_name.isnot(None)
        )
    ).group_by(Element.material_name)

    material_result = await session.execute(material_query)
    by_material = {row.material_name: row.count for row in material_result}

    # Get geometry/property statistics
    stats_query = select(
        func.count(Element.id).label('total'),
        func.count().filter(Element.has_geometry == True).label('with_geometry'),
        func.count().filter(Element.has_properties == True).label('with_properties'),
        func.count().filter(Element.has_materials == True).label('with_materials'),
        func.sum(Element.area).label('total_area'),
        func.sum(Element.volume).label('total_volume')
    ).where(Element.project_id == project.id)

    stats_result = await session.execute(stats_query)
    stats = stats_result.first()

    # Get unique levels and buildings
    spatial_query = select(
        func.array_agg(func.distinct(Element.level_name)).label('levels'),
        func.array_agg(func.distinct(Element.building_name)).label('buildings')
    ).where(Element.project_id == project.id)

    spatial_result = await session.execute(spatial_query)
    spatial = spatial_result.first()

    return ElementSummaryResponse(
        project_id=project_id,
        total_elements=stats.total,
        by_ifc_type=by_ifc_type,
        by_element_type={},  # Would need to calculate
        by_level=by_level,
        by_material=by_material,
        with_geometry=stats.with_geometry,
        with_properties=stats.with_properties,
        with_materials=stats.with_materials,
        levels=[level for level in (spatial.levels or []) if level],
        buildings=[building for building in (spatial.buildings or []) if building],
        data_completeness={
            "geometry": (stats.with_geometry / stats.total * 100) if stats.total > 0 else 0,
            "properties": (stats.with_properties / stats.total * 100) if stats.total > 0 else 0,
            "materials": (stats.with_materials / stats.total * 100) if stats.total > 0 else 0
        },
        common_properties=[],  # Would need to analyze property frequency
        total_area={"value": float(stats.total_area), "unit": "m2"} if stats.total_area else None,
        total_volume={"value": float(stats.total_volume), "unit": "m3"} if stats.total_volume else None,
        total_length=None  # Would need to calculate
    )