File size: 30,003 Bytes
d15f07c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
"""
FastAPI application optimized for Databricks Apps deployment.
Serves React frontend and provides REST API for agent interactions.
"""
from typing import List, Dict, Any, Optional
from datetime import datetime
from pathlib import Path
from fastapi import FastAPI, HTTPException, Query, BackgroundTasks
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware

from api.static_cache import CachedStaticFiles
from pydantic import BaseModel, Field
from loguru import logger
import os

from agents.orchestrator import OrchestratorAgent
from ingestion.delta_lake import DeltaLakePipeline
from config import settings

# Initialize FastAPI app
app = FastAPI(
    title="Open Navigator",
    description="AI-powered advocacy opportunity finder",
    version="2.0.0",
    docs_url="/api/docs",
    redoc_url="/api/redoc",
    openapi_url="/api/openapi.json"
)

# Add CORS middleware. Origins come from an explicit env-driven allowlist
# (api/origins.py), never "*": with allow_credentials=True, Starlette reflects
# the caller's Origin, so "*" would trust every site on the internet.
from api.origins import allowed_origins

app.add_middleware(
    CORSMiddleware,
    allow_origins=list(allowed_origins()),
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Compress responses (notably the large /data JSON marts — county_metrics is
# ~2.6MB, jurisdiction_mapping_quality ~6.6MB; both compress ~5-10x).
app.add_middleware(GZipMiddleware, minimum_size=1000)

# Initialize components
orchestrator = OrchestratorAgent()
pipeline = DeltaLakePipeline()

# Pydantic models
class WorkflowRequest(BaseModel):
    """Request to start a new analysis workflow."""
    targets: List[Dict[str, str]]
    topics: Optional[List[str]] = None

class OpportunityFilter(BaseModel):
    """Filter criteria for advocacy opportunities."""
    state: Optional[str] = None
    topic: Optional[str] = None
    urgency: Optional[str] = None
    min_confidence: Optional[float] = 0.7


# API Routes
@app.get("/api/health")
async def health_check():
    """Health check endpoint."""
    return {"status": "healthy", "timestamp": datetime.utcnow().isoformat()}


@app.get("/api/dashboard")
async def get_dashboard_stats():
    """Get dashboard statistics and recent opportunities."""
    try:
        # Query Delta Lake for stats
        stats = await pipeline.get_dashboard_stats()
        return stats
    except Exception as e:
        logger.error(f"Dashboard stats error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/api/opportunities")
async def get_opportunities(
    state: Optional[str] = Query(None),
    topic: Optional[str] = Query(None),
    urgency: Optional[str] = Query(None),
    limit: int = Query(100, le=1000)
):
    """Get advocacy opportunities with optional filters."""
    try:
        opportunities = await pipeline.query_opportunities(
            state=state,
            topic=topic,
            urgency=urgency,
            limit=limit
        )
        return {"opportunities": opportunities, "count": len(opportunities)}
    except Exception as e:
        logger.error(f"Query opportunities error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/api/documents")
async def get_documents(
    search: Optional[str] = Query(None),
    page: int = Query(1, ge=1),
    limit: int = Query(20, le=100)
):
    """Get analyzed documents with pagination."""
    try:
        offset = (page - 1) * limit
        documents = await pipeline.query_documents(
            search=search,
            limit=limit,
            offset=offset
        )
        total = await pipeline.count_documents(search=search)
        return {
            "documents": documents,
            "page": page,
            "limit": limit,
            "total": total,
            "total_pages": (total + limit - 1) // limit
        }
    except Exception as e:
        logger.error(f"Query documents error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/api/search/")
async def search_all(
    q: str = Query(..., min_length=1, description="Search query"),
    types: Optional[str] = Query("contacts,organizations,causes", description="Comma-separated types to search"),
    state: Optional[str] = Query(None, description="Filter by state code (e.g. MA, AL)"),
    limit: int = Query(10, ge=1, le=100),
    page: int = Query(1, ge=1),
    ntee_code: Optional[str] = Query(None, description="NTEE category code")
):
    """
    Unified search across contacts, organizations, causes, and jurisdictions.
    Returns results grouped by type with pagination.
    """
    try:
        offset = (page - 1) * limit
        search_types = [t.strip() for t in types.split(',') if t.strip()]
        
        # Initialize results structure
        results = {
            "contacts": [],
            "organizations": [],
            "causes": [],
            "meetings": [],
            "jurisdictions": []
        }
        
        # Search logic (placeholder - implement actual search)
        # For now, return mock results for demonstration
        if "contacts" in search_types:
            results["contacts"] = [
                {
                    "type": "contact",
                    "title": f"Sample Contact matching '{q}'",
                    "subtitle": "Government Official",
                    "description": "Contact information for local official",
                    "url": "/contact/1",
                    "score": 0.9,
                    "metadata": {"state": state or "MA"}
                }
            ]
        
        if "organizations" in search_types:
            results["organizations"] = [
                {
                    "type": "organization",
                    "title": f"Sample Organization matching '{q}'",
                    "subtitle": "Nonprofit Organization",
                    "description": "Community health organization",
                    "url": "/org/1",
                    "score": 0.85,
                    "metadata": {"state": state or "MA", "ntee": ntee_code}
                }
            ]
        
        if "causes" in search_types:
            results["causes"] = [
                {
                    "type": "cause",
                    "title": f"Sample Cause matching '{q}'",
                    "subtitle": "Health & Wellness",
                    "description": "Advocacy for community health",
                    "url": "/cause/1",
                    "score": 0.8,
                    "metadata": {}
                }
            ]
        
        # Calculate total results
        total_results = sum(len(v) for v in results.values())
        total_pages = max(1, (total_results + limit - 1) // limit)
        
        return {
            "query": q,
            "total_results": total_results,
            "results": results,
            "pagination": {
                "page": page,
                "limit": limit,
                "offset": offset,
                "total_pages": total_pages,
                "has_next": page < total_pages,
                "has_prev": page > 1
            },
            "filters": {
                "state": state,
                "ntee_code": ntee_code,
                "types": search_types
            }
        }
    except Exception as e:
        logger.error(f"Search error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/api/workflow/start")
async def start_workflow(request: WorkflowRequest, background_tasks: BackgroundTasks):
    """Start a new analysis workflow."""
    try:
        workflow_id = f"workflow_{datetime.utcnow().timestamp()}"
        
        # Start workflow in background
        background_tasks.add_task(
            orchestrator.execute_pipeline,
            workflow_id=workflow_id,
            targets=request.targets,
            topics=request.topics
        )
        
        return {
            "workflow_id": workflow_id,
            "status": "started",
            "message": "Workflow started successfully"
        }
    except Exception as e:
        logger.error(f"Workflow start error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/api/workflow/{workflow_id}/status")
async def get_workflow_status(workflow_id: str):
    """Get status of a running workflow."""
    try:
        status = await orchestrator.get_workflow_status(workflow_id)
        return status
    except Exception as e:
        logger.error(f"Workflow status error: {e}")
        raise HTTPException(status_code=404, detail="Workflow not found")


@app.post("/api/advocacy/email/{opportunity_id}")
async def generate_advocacy_email(opportunity_id: str):
    """Generate advocacy email for an opportunity."""
    try:
        opportunity = await pipeline.get_opportunity(opportunity_id)
        if not opportunity:
            raise HTTPException(status_code=404, detail="Opportunity not found")
        
        email_content = await orchestrator.generate_advocacy_email(opportunity)
        return {"content": email_content}
    except Exception as e:
        logger.error(f"Generate email error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/api/settings")
async def get_settings():
    """Get current system settings."""
    return {
        "target_states": settings.target_states or [],
        "policy_topics": settings.policy_topics,
        "min_confidence": 0.7,
        "email_notifications": False,
        "notification_email": ""
    }


@app.put("/api/settings")
async def update_settings(new_settings: Dict[str, Any]):
    """Update system settings."""
    try:
        # In production, this would update configuration in Unity Catalog
        logger.info(f"Settings update requested: {new_settings}")
        return {"message": "Settings updated successfully"}
    except Exception as e:
        logger.error(f"Settings update error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/api/agents/status")
async def get_agents_status():
    """Get status of all agents."""
    try:
        return {
            "agents": [
                {"name": "Scraper", "status": "active", "uptime": "24h"},
                {"name": "Classifier", "status": "active", "uptime": "24h"},
                {"name": "Sentiment Analyzer", "status": "active", "uptime": "24h"},
                {"name": "Advocacy Writer", "status": "active", "uptime": "24h"}
            ]
        }
    except Exception as e:
        logger.error(f"Agent status error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/api/nonprofits")
async def search_nonprofits(
    location: str = Query("Tuscaloosa, AL", description="City, State format"),
    keyword: Optional[str] = Query(None, description="Service keyword (e.g., 'dental', 'health')"),
    state: Optional[str] = Query(None, description="2-letter state code (e.g., 'AL')"),
    ntee_code: Optional[str] = Query(None, description="NTEE code (e.g., 'E' for health)"),
    source: Optional[str] = Query(None, description="Data source: 'propublica', 'everyorg', 'all'")
):
    """
    Search for nonprofits using free open data APIs.
    
    Integrates data from:
    - ProPublica Nonprofit Explorer (financial data, NTEE codes)
    - Every.org (mission statements, logos)
    - IRS TEOS (official tax-exempt status)
    
    Example: /api/nonprofits?location=Tuscaloosa,AL&keyword=dental&ntee_code=E
    """
    try:
        from scrapers.irs.nonprofit_discovery import NonprofitDiscovery
        
        discovery = NonprofitDiscovery()
        results = []
        
        # Parse location for state/city
        location_parts = location.split(',')
        city = location_parts[0].strip() if len(location_parts) > 0 else None
        state_from_location = location_parts[1].strip() if len(location_parts) > 1 else None
        state_code = state or state_from_location or "AL"
        
        # Determine which sources to query
        sources_to_query = ['propublica', 'everyorg'] if source == 'all' or not source else [source]
        
        # Query ProPublica
        if 'propublica' in sources_to_query:
            try:
                propublica_results = discovery.search_propublica(
                    state=state_code,
                    city=city,
                    ntee_code=ntee_code
                )
                results.extend(propublica_results)
                logger.info(f"ProPublica: Found {len(propublica_results)} organizations")
            except Exception as e:
                logger.warning(f"ProPublica search failed: {e}")
        
        # Query Every.org
        if 'everyorg' in sources_to_query:
            try:
                causes = []
                if keyword:
                    # Map keywords to causes
                    keyword_lower = keyword.lower()
                    if 'health' in keyword_lower or 'dental' in keyword_lower or 'medical' in keyword_lower:
                        causes.append('health')
                    if 'education' in keyword_lower or 'school' in keyword_lower:
                        causes.append('education')
                
                everyorg_results = discovery.search_everyorg(
                    location=location,
                    causes=causes if causes else None
                )
                results.extend(everyorg_results)
                logger.info(f"Every.org: Found {len(everyorg_results)} organizations")
            except Exception as e:
                logger.warning(f"Every.org search failed: {e}")
        
        # Filter by keyword if provided
        if keyword and results:
            keyword_lower = keyword.lower()
            filtered_results = []
            for org in results:
                # Search in name, description, mission, ntee_description
                searchable_text = ' '.join([
                    str(org.get('name', '')),
                    str(org.get('description', '')),
                    str(org.get('mission', '')),
                    str(org.get('ntee_description', ''))
                ]).lower()
                
                if keyword_lower in searchable_text:
                    filtered_results.append(org)
            
            results = filtered_results
        
        return {
            "location": location,
            "keyword": keyword,
            "state": state_code,
            "ntee_code": ntee_code,
            "count": len(results),
            "nonprofits": results,
            "data_sources": {
                "propublica": "https://projects.propublica.org/nonprofits/api",
                "everyorg": "https://www.every.org/nonprofit-api",
                "irs_teos": "https://www.irs.gov/charities-non-profits/tax-exempt-organization-search-bulk-data-downloads"
            }
        }
        
    except Exception as e:
        logger.error(f"Nonprofit search error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/api/nonprofits/compensation")
async def nonprofit_compensation(
    ein: Optional[str] = Query(None, description="Exact EIN — a single org's people"),
    state: Optional[str] = Query(None, description="2-letter state code or full name"),
    person: Optional[str] = Query(None, description="Case-insensitive person-name search"),
    min_comp: Optional[int] = Query(None, description="Minimum reportable comp from the org"),
    limit: int = Query(25, ge=1, le=200),
    offset: int = Query(0, ge=0),
    sort: str = Query("comp-desc", description="comp-desc | comp-asc | name-asc"),
):
    """
    Person-level executive/board compensation from the GivingTuesday 990 datamarts
    (Form 990 Part VII-A + Schedule J detail), joined to organization context.

    Examples:
      /api/nonprofits/compensation?ein=530196605            (one org's people)
      /api/nonprofits/compensation?state=NY&min_comp=500000 (top earners in NY)
      /api/nonprofits/compensation?person=smith&sort=comp-desc
    """
    from api.routes import search_postgres
    try:
        records = await search_postgres.get_nonprofit_compensation_pg(
            ein=ein, state=state, person=person, min_comp=min_comp,
            limit=limit, offset=offset, sort=sort,
        )
        return {"count": len(records), "results": records}
    except Exception as e:
        logger.error(f"Compensation endpoint error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/api/data/status")
async def get_data_status():
    """
    Get status of all reference data ingestions.
    
    Returns counts and last update times for:
    - Census jurisdictions
    - NCES school districts
    - Nonprofit organizations
    - Meeting datasets (MeetingBank, LocalView, etc.)

    Every count is a real warehouse value (see
    ``stats_neon.fetch_national_reference_counts``) or ``null`` when it can't be
    computed — never a hard-coded estimate (CLAUDE.md, "No Fabricated Data").
    """
    try:
        from api.routes.stats_neon import fetch_national_reference_counts

        counts = await fetch_national_reference_counts()
        last_updated = counts.get("last_updated")

        def _entry(path: str, count: Optional[int]) -> Dict[str, Any]:
            return {
                "path": path,
                "status": "available" if count is not None else "unavailable",
                "count": count,
                "last_updated": last_updated if count is not None else None,
            }

        aggregate = "public.jurisdiction_state_aggregate (national)"
        # Per-source meeting counts are not modeled in `public`; unavailable, not guessed.
        unavailable_meetings = {"status": "unavailable", "count": None}
        return {
            "census_jurisdictions": _entry(aggregate, counts["jurisdictions"]),
            "nces_school_districts": _entry(aggregate, counts["school_districts"]),
            "nonprofits": _entry(aggregate, counts["nonprofits"]),
            "meeting_datasets": {
                "meetingbank": dict(unavailable_meetings),
                "city_scrapers": dict(unavailable_meetings),
                "open_states": dict(unavailable_meetings),
            },
        }

    except Exception as e:
        logger.error(f"Data status error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/api/data/ingest/census")
async def ingest_census_data(background_tasks: BackgroundTasks):
    """
    Trigger Census Bureau jurisdiction data ingestion.
    
    Downloads and processes:
    - 3,144 counties
    - 19,500+ municipalities  
    - 36,000+ townships
    - 13,000+ school districts
    
    This is a long-running operation that runs in the background.
    """
    try:
        def run_census_ingestion():
            from scripts.discovery.census_ingestion import CensusGovernmentIngestion
            import asyncio
            
            logger.info("Starting Census data ingestion...")
            ingestor = CensusGovernmentIngestion()
            
            # Run async ingestion
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            result = loop.run_until_complete(ingestor.ingest_all_jurisdictions())
            loop.close()
            
            logger.success(f"Census ingestion complete: {result}")
        
        background_tasks.add_task(run_census_ingestion)
        
        return {
            "message": "Census data ingestion started",
            "status": "processing",
            "check_status": "/api/data/status"
        }
        
    except Exception as e:
        logger.error(f"Census ingestion error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/api/data/ingest/nces")
async def ingest_nces_data(background_tasks: BackgroundTasks):
    """
    Trigger NCES school district data ingestion.
    
    Downloads and processes 13,000+ school districts with:
    - District names and addresses
    - Contact information
    - NCES IDs
    - Enrollment data
    """
    try:
        def run_nces_ingestion():
            from scripts.discovery.nces_ingestion import NCESSchoolDistrictIngestion
            import asyncio
            
            logger.info("Starting NCES data ingestion...")
            ingestor = NCESSchoolDistrictIngestion()
            
            # Run async ingestion
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            result = loop.run_until_complete(ingestor.download_and_process())
            loop.close()
            
            logger.success(f"NCES ingestion complete: {result}")
        
        background_tasks.add_task(run_nces_ingestion)
        
        return {
            "message": "NCES data ingestion started",
            "status": "processing",
            "check_status": "/api/data/status"
        }
        
    except Exception as e:
        logger.error(f"NCES ingestion error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/api/data/ingest/nonprofits")
async def ingest_nonprofits(
    state: str = Query(..., description="2-letter state code"),
    ntee_codes: Optional[List[str]] = Query(None, description="NTEE codes to ingest"),
    background_tasks: BackgroundTasks = None
):
    """
    Trigger nonprofit data ingestion for a specific state.
    
    Bulk downloads nonprofit data from ProPublica API and caches locally.
    
    Example: POST /api/data/ingest/nonprofits?state=AL&ntee_codes=E&ntee_codes=E20
    """
    try:
        from scrapers.irs.nonprofit_discovery import NonprofitDiscovery
        
        discovery = NonprofitDiscovery()
        ntee_list = ntee_codes or ["E"]  # Default to health
        
        total_orgs = 0
        for ntee_code in ntee_list:
            orgs = discovery.search_propublica(state=state, ntee_code=ntee_code)
            total_orgs += len(orgs)
            logger.info(f"Cached {len(orgs)} nonprofits for {state}/{ntee_code}")
        
        return {
            "message": f"Nonprofit data ingestion complete for {state}",
            "state": state,
            "ntee_codes": ntee_list,
            "organizations_cached": total_orgs,
            "cache_location": "data/cache/nonprofits"
        }
        
    except Exception as e:
        logger.error(f"Nonprofit ingestion error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/api/jurisdictions")
async def get_jurisdictions(
    state: Optional[str] = Query(None, description="2-letter state code"),
    type: Optional[str] = Query(None, description="Type: county, municipality, township"),
    limit: int = Query(100, le=1000)
):
    """
    Query ingested Census jurisdiction data.
    
    Returns government entities with FIPS codes, coordinates, and population.
    """
    try:
        # This would query the Delta Lake census tables
        # For now, return sample data
        return {
            "message": "Query census jurisdiction data from Delta Lake",
            "filters": {"state": state, "type": type},
            "limit": limit,
            "note": "Requires Census data ingestion first (POST /api/data/ingest/census)",
            "example_data": [
                {
                    "name": "Tuscaloosa County",
                    "state": "AL",
                    "type": "county",
                    "fips": "01125",
                    "population": "209355"
                }
            ]
        }
        
    except Exception as e:
        logger.error(f"Jurisdiction query error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/api/school-districts")
async def get_school_districts(
    state: Optional[str] = Query(None, description="2-letter state code"),
    limit: int = Query(100, le=1000)
):
    """
    Query ingested NCES school district data.
    
    Returns school districts with contact information and enrollment.
    """
    try:
        # This would query the Delta Lake NCES tables
        return {
            "message": "Query NCES school district data from Delta Lake",
            "filters": {"state": state},
            "limit": limit,
            "note": "Requires NCES data ingestion first (POST /api/data/ingest/nces)",
            "example_data": [
                {
                    "name": "Tuscaloosa City Schools",
                    "state": "AL",
                    "nces_id": "0100123",
                    "phone": "(205) 759-3500",
                    "website": "https://www.tusc.k12.al.us/"
                }
            ]
        }
        
    except Exception as e:
        logger.error(f"School district query error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# Batch job dashboard (caption/analyze pipelines)
from api.routes import batch_jobs as batch_jobs_routes

app.include_router(batch_jobs_routes.router, prefix="/api")

# Prod deployment jobs (database → Neon prod, web → HuggingFace)
from api.routes import deployments as deployments_routes

app.include_router(deployments_routes.router, prefix="/api")

# Data-center job claims by phase (#246): GET /api/data-centers/job-claims
from api.routes import data_centers as data_centers_routes
from api.routes import data_center_comments as data_center_comments_routes
from api.routes import data_center_drill as data_center_drill_routes

app.include_router(data_centers_routes.router, prefix="/api")
app.include_router(data_center_comments_routes.router, prefix="/api")
app.include_router(data_center_drill_routes.router, prefix="/api")
# Data center sites over time and recording coverage (#1348).
from api.routes import data_center_sites_timeline as data_center_sites_timeline_routes
from api.routes import recorded_coverage as recorded_coverage_routes

app.include_router(data_center_sites_timeline_routes.router, prefix="/api")
app.include_router(recorded_coverage_routes.router, prefix="/api")
# Data-center job-application links (#248): public list + admin screen.
from api.routes import application_links as application_links_routes

app.include_router(application_links_routes.public_router, prefix="/api")
app.include_router(application_links_routes.admin_router, prefix="/api")
from api.routes import meeting_kind_reviews as meeting_kind_reviews_routes

app.include_router(meeting_kind_reviews_routes.admin_router, prefix="/api")
# Official profile claims + pending edits (#1062). Router prefix is "/people".
from api.routes import person_claims as person_claims_routes

app.include_router(person_claims_routes.router, prefix="/api")

# Serve React frontend
static_dir = Path(__file__).parent / "static"
if static_dir.exists():
    # Mount static files (JS, CSS, images)
    app.mount("/assets", StaticFiles(directory=static_dir / "assets"), name="assets")

    # Public /data tree, served the same paths as Vite dev. Covers the ACS
    # map/scorecard marts (/data/census-map), the per-state ZCTA (ZIP) tiles
    # (/data/zctas — the lowest drilldown tier), and the jurisdiction-quality
    # snapshot. Mounting only /data/census-map left the others 404ing.
    web_app_public = Path(__file__).parent.parent / "web_app" / "public"
    data_dir = web_app_public / "data"
    if data_dir.is_dir():
        app.mount("/data", CachedStaticFiles(directory=data_dir), name="public_data")
    else:
        logger.warning(f"Public data bundle missing (expected {data_dir})")

    # Serve index.html for all non-API routes (SPA routing)
    @app.get("/{full_path:path}")
    async def serve_react_app(full_path: str):
        """Serve a real static file if one exists, else the React app (SPA routing).

        Top-level public assets (e.g. /pdf/*, /communityone_logo.svg,
        /robots.txt, /wikimedia/*) live in static_dir but are not under the
        mounted /assets or /data trees. Without this file check they fall through
        to index.html, so the browser loads the SPA into e.g. an <iframe
        src="/pdf/..."> and React Router renders the NotFound (404) page instead
        of the file. Vite's dev server serves these from public/ at the root, so
        the gap only shows in production.
        """
        if full_path.startswith("api/"):
            raise HTTPException(status_code=404, detail="API endpoint not found")

        # Serve a concrete static file when the path resolves to one inside
        # static_dir (path-traversal guarded via relative_to).
        if full_path:
            candidate = (static_dir / full_path).resolve()
            try:
                candidate.relative_to(static_dir.resolve())
            except ValueError:
                candidate = None
            if candidate is not None and candidate.is_file():
                return FileResponse(candidate)

        index_file = static_dir / "index.html"
        if index_file.exists():
            return FileResponse(index_file)
        else:
            raise HTTPException(status_code=404, detail="Frontend not built")


@app.on_event("startup")
async def startup_event():
    """Initialize system on startup."""
    logger.info("Starting CommunityOne Open Navigator application...")
    
    # Initialize Delta Lake if not exists
    try:
        await pipeline.initialize_tables()
        logger.info("Delta Lake tables initialized")
    except Exception as e:
        logger.warning(f"Delta Lake initialization skipped: {e}")
    
    logger.info("Application started successfully")


@app.on_event("shutdown")
async def shutdown_event():
    """Cleanup on shutdown."""
    logger.info("Shutting down application...")


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "api.app:app",
        host="0.0.0.0",
        port=8001,
        reload=True
    )