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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
"""
Feed-personalization API: a user's saved locations, lenses, and signals.

Backs the /feed-setup screen. Reads/writes three operational ORM tables
(user_locations / user_lens_prefs / user_signal_prefs — see api/models.py),
keyed to the authenticated user. NO transformation/SQL logic lives here beyond
straight ORM CRUD; these are operational user-preference tables, not dbt marts.

Endpoints:
  - GET  /api/feed/config   (auth)    -> assembled config for the current user
  - PUT  /api/feed/config   (auth)    -> full-replace the config in one txn
  - GET  /api/feed/places   (no auth) -> place typeahead (Nominatim proxy reuse)

Lens/signal slugs are validated against server-side allow-sets so junk can't be
stored. Place results carry only real geocoder hits — no fabricated/placeholder
data (CLAUDE.md).
"""
from __future__ import annotations

import re
from typing import Any, List, Optional

from fastapi import APIRouter, Depends, HTTPException, Query, status
from loguru import logger
from opentelemetry import trace
from pydantic import BaseModel, field_validator
from sqlalchemy.orm import Session

from api.auth import get_current_user
from api.database import get_db
from api.models import User, UserLocation, UserLensPref, UserSignalPref
from api.routes.geocode import _throttled_get

router = APIRouter(prefix="/feed", tags=["feed"])

tracer = trace.get_tracer(__name__)

_US_ZIP_RE = re.compile(r"^(\d{5})(?:-\d{4})?$")


# ---------------------------------------------------------------------------
# Server-side allow-sets. Labels/copy live in the frontend; only slugs here.
# ---------------------------------------------------------------------------
ALLOWED_LENSES = frozenset({
    "family-first",
    "faith-community",
    "charitable-impact",
    "neighborhood-life",
    "education",
    "local-economy",
})

ALLOWED_SIGNALS = frozenset({
    "contested",
    "money-moves",
    "raised-eyebrows",
    "moving-fast",
    "slipped-through",
    "helping-hands",
    "watch-next",
})

ALLOWED_SHARED_LEVELS = frozenset({"street", "district", "city", "county", "state"})


# ---------------------------------------------------------------------------
# Pydantic models (inline, mirroring lenses.py convention).
# ---------------------------------------------------------------------------
class LocationIn(BaseModel):
    """A location as submitted on save (resolved geo all optional)."""
    name: str
    city: Optional[str] = None
    shared_level: str = "city"
    is_primary: bool = False
    state_code: Optional[str] = None
    state: Optional[str] = None
    county: Optional[str] = None
    place_fips: Optional[str] = None
    county_fips: Optional[str] = None
    latitude: Optional[float] = None
    longitude: Optional[float] = None
    jurisdiction_id: Optional[str] = None

    @field_validator("shared_level")
    @classmethod
    def _check_shared_level(cls, v: str) -> str:
        if v not in ALLOWED_SHARED_LEVELS:
            raise ValueError(
                f"shared_level must be one of {sorted(ALLOWED_SHARED_LEVELS)} (got '{v}')"
            )
        return v


class LocationOut(BaseModel):
    """A saved location as returned to the client."""
    id: int
    name: str
    shared_level: str
    is_primary: bool
    state_code: Optional[str] = None
    state: Optional[str] = None
    county: Optional[str] = None
    latitude: Optional[float] = None
    longitude: Optional[float] = None
    jurisdiction_id: Optional[str] = None


class FeedConfigIn(BaseModel):
    """Full feed config submitted on save (full replace)."""
    locations: List[LocationIn] = []
    lenses: List[str] = []
    signals: List[str] = []

    @field_validator("lenses")
    @classmethod
    def _check_lenses(cls, v: List[str]) -> List[str]:
        unknown = [s for s in v if s not in ALLOWED_LENSES]
        if unknown:
            raise ValueError(f"unknown lens slug(s): {unknown}")
        # De-dupe while preserving order.
        return list(dict.fromkeys(v))

    @field_validator("signals")
    @classmethod
    def _check_signals(cls, v: List[str]) -> List[str]:
        unknown = [s for s in v if s not in ALLOWED_SIGNALS]
        if unknown:
            raise ValueError(f"unknown signal slug(s): {unknown}")
        return list(dict.fromkeys(v))


class FeedConfigOut(BaseModel):
    """Assembled feed config returned by GET/PUT."""
    locations: List[LocationOut]
    lenses: List[str]
    signals: List[str]
    profile_completed: bool


class PlaceHit(BaseModel):
    """One real geocoder hit for the place typeahead."""
    name: str
    city: Optional[str] = None
    county: Optional[str] = None
    state: Optional[str] = None
    state_code: Optional[str] = None
    postal_code: Optional[str] = None
    latitude: float
    longitude: float


class PlacesResponse(BaseModel):
    results: List[PlaceHit]


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _require_user(user: Optional[User]) -> User:
    """get_current_user returns Optional[User]; enforce auth here."""
    if user is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Authentication required",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return user


def _assemble_config(db: Session, user: User) -> FeedConfigOut:
    """Read the three preference tables and shape the config response."""
    locations = (
        db.query(UserLocation)
        .filter(UserLocation.user_id == user.user_id)
        .order_by(UserLocation.is_primary.desc(), UserLocation.id.asc())
        .all()
    )
    lenses = (
        db.query(UserLensPref.lens_slug)
        .filter(UserLensPref.user_id == user.user_id)
        .order_by(UserLensPref.lens_slug.asc())
        .all()
    )
    signals = (
        db.query(UserSignalPref.signal_slug)
        .filter(UserSignalPref.user_id == user.user_id)
        .order_by(UserSignalPref.signal_slug.asc())
        .all()
    )
    return FeedConfigOut(
        locations=[
            LocationOut(
                id=loc.id,
                name=loc.name,
                shared_level=loc.shared_level,
                is_primary=bool(loc.is_primary),
                state_code=loc.state_code,
                state=loc.state,
                county=loc.county,
                latitude=loc.latitude,
                longitude=loc.longitude,
                jurisdiction_id=loc.jurisdiction_id,
            )
            for loc in locations
        ],
        lenses=[row[0] for row in lenses],
        signals=[row[0] for row in signals],
        profile_completed=bool(user.profile_completed),
    )


# 2-letter -> full state name, for syncing the primary location into
# User.state when only a state_code came back from the geocoder.
_STATE_CODE_TO_NAME = {
    "AL": "Alabama", "AK": "Alaska", "AZ": "Arizona", "AR": "Arkansas",
    "CA": "California", "CO": "Colorado", "CT": "Connecticut", "DE": "Delaware",
    "FL": "Florida", "GA": "Georgia", "HI": "Hawaii", "ID": "Idaho",
    "IL": "Illinois", "IN": "Indiana", "IA": "Iowa", "KS": "Kansas",
    "KY": "Kentucky", "LA": "Louisiana", "ME": "Maine", "MD": "Maryland",
    "MA": "Massachusetts", "MI": "Michigan", "MN": "Minnesota", "MS": "Mississippi",
    "MO": "Missouri", "MT": "Montana", "NE": "Nebraska", "NV": "Nevada",
    "NH": "New Hampshire", "NJ": "New Jersey", "NM": "New Mexico", "NY": "New York",
    "NC": "North Carolina", "ND": "North Dakota", "OH": "Ohio", "OK": "Oklahoma",
    "OR": "Oregon", "PA": "Pennsylvania", "RI": "Rhode Island", "SC": "South Carolina",
    "SD": "South Dakota", "TN": "Tennessee", "TX": "Texas", "UT": "Utah",
    "VT": "Vermont", "VA": "Virginia", "WA": "Washington", "WV": "West Virginia",
    "WI": "Wisconsin", "WY": "Wyoming", "DC": "District of Columbia",
}

_STATE_NAME_TO_CODE = {name.lower(): code for code, name in _STATE_CODE_TO_NAME.items()}


def _extract_primary_city(primary_loc: LocationIn) -> Optional[str]:
    """Derive a clean city label from LocationIn for User.city synchronization."""
    if primary_loc.city and primary_loc.city.strip():
        return primary_loc.city.strip()
    city = (primary_loc.name or "").strip()
    if not city:
        return None
    if primary_loc.state_code and city.endswith(f", {primary_loc.state_code}"):
        city = city[: -len(f", {primary_loc.state_code}")].strip()
    if "," in city:
        city = city.split(",", 1)[0].strip()
    return city or None


# ---------------------------------------------------------------------------
# Endpoints
# ---------------------------------------------------------------------------
@router.get("/config", response_model=FeedConfigOut)
def get_feed_config(
    user: Optional[User] = Depends(get_current_user),
    db: Session = Depends(get_db),
) -> FeedConfigOut:
    """Return the current user's saved feed config (locations/lenses/signals)."""
    user = _require_user(user)
    with tracer.start_as_current_span("feed.get_config") as span:
        span.set_attribute("feed.user_id", user.user_id)
        return _assemble_config(db, user)


@router.put("/config", response_model=FeedConfigOut)
def put_feed_config(
    body: FeedConfigIn,
    user: Optional[User] = Depends(get_current_user),
    db: Session = Depends(get_db),
) -> FeedConfigOut:
    """Full-replace the current user's feed config in a single transaction.

    Deletes all existing rows for the user across the three tables, inserts the
    submitted ones, marks the profile complete, and syncs the primary location's
    city/county/state back into User.city/county/state so Profile.tsx keeps
    rendering the "city, state" header.
    """
    user = _require_user(user)

    with tracer.start_as_current_span("feed.put_config") as span:
        span.set_attribute("feed.user_id", user.user_id)
        span.set_attribute("feed.locations", len(body.locations))
        span.set_attribute("feed.lenses", len(body.lenses))
        span.set_attribute("feed.signals", len(body.signals))

        try:
            # Full replace: clear the user's existing rows in all three tables.
            db.query(UserLocation).filter(UserLocation.user_id == user.user_id).delete(
                synchronize_session=False
            )
            db.query(UserLensPref).filter(UserLensPref.user_id == user.user_id).delete(
                synchronize_session=False
            )
            db.query(UserSignalPref).filter(UserSignalPref.user_id == user.user_id).delete(
                synchronize_session=False
            )

            # If nothing is flagged primary, treat the first location as primary.
            has_primary = any(loc.is_primary for loc in body.locations)
            primary_loc: Optional[LocationIn] = None
            for idx, loc in enumerate(body.locations):
                is_primary = loc.is_primary or (not has_primary and idx == 0)
                if is_primary and primary_loc is None:
                    primary_loc = loc
                db.add(UserLocation(
                    user_id=user.user_id,
                    name=loc.name,
                    shared_level=loc.shared_level,
                    is_primary=is_primary,
                    state_code=loc.state_code,
                    state=loc.state,
                    county=loc.county,
                    place_fips=loc.place_fips,
                    county_fips=loc.county_fips,
                    latitude=loc.latitude,
                    longitude=loc.longitude,
                    jurisdiction_id=loc.jurisdiction_id,
                ))

            for slug in body.lenses:
                db.add(UserLensPref(user_id=user.user_id, lens_slug=slug))
            for slug in body.signals:
                db.add(UserSignalPref(user_id=user.user_id, signal_slug=slug))

            # Sync the primary location into the existing User.* columns so the
            # legacy Profile.tsx "city, state" header keeps working.
            if primary_loc is not None:
                resolved_state = primary_loc.state
                if not resolved_state and primary_loc.state_code:
                    resolved_state = _STATE_CODE_TO_NAME.get(
                        primary_loc.state_code.upper(), primary_loc.state_code
                    )
                user.county = primary_loc.county
                user.state = resolved_state
                user.city = _extract_primary_city(primary_loc)

            user.profile_completed = True

            db.commit()
        except Exception as exc:  # noqa: BLE001 — roll back, surface a clean 500
            db.rollback()
            span.record_exception(exc)
            logger.error("Feed config save failed for user {}: {}", user.user_id, exc)
            raise HTTPException(status_code=500, detail="Failed to save feed config")

        db.refresh(user)
        return _assemble_config(db, user)


def _derive_state_code(address: dict) -> Optional[str]:
    """Pull a 2-letter US state code from a Nominatim address block.

    Prefers ISO3166-2-lvl4 ("US-AL" -> "AL"); falls back to `state` when it is
    either a known 2-letter USPS code or a full US state name (never invents one).
    """
    iso = address.get("ISO3166-2-lvl4")
    if isinstance(iso, str) and "-" in iso:
        code = iso.split("-", 1)[1].strip().upper()
        if code in _STATE_CODE_TO_NAME:
            return code
    state = address.get("state")
    if isinstance(state, str):
        cleaned = state.strip()
        if len(cleaned) == 2 and cleaned.upper() in _STATE_CODE_TO_NAME:
            return cleaned.upper()
        mapped = _STATE_NAME_TO_CODE.get(cleaned.lower())
        if mapped:
            return mapped
    return None


def _extract_municipality(address: dict) -> Optional[str]:
    """Extract municipality/place name from a Nominatim address dictionary."""
    return (
        address.get("city")
        or address.get("town")
        or address.get("village")
        or address.get("hamlet")
        or address.get("municipality")
        or address.get("suburb")
    )


async def _fetch_nominatim_candidates(query: str) -> tuple[List[dict[str, Any]], Optional[str]]:
    """Fetch Nominatim candidate items for a free-text or US ZIP query."""
    zip_match = _US_ZIP_RE.match(query)
    if not zip_match:
        payload = await _throttled_get(
            "/search",
            {
                "q": query,
                "format": "json",
                "addressdetails": "1",
                "countrycodes": "us",
                "limit": "6",
            },
        )
        return (payload if isinstance(payload, list) else []), None

    zip5 = zip_match.group(1)
    payload = await _throttled_get(
        "/search",
        {
            "postalcode": zip5,
            "format": "json",
            "addressdetails": "1",
            "countrycodes": "us",
            "limit": "6",
        },
    )
    items: List[dict[str, Any]] = payload if isinstance(payload, list) else []
    if not items:
        fallback = await _throttled_get(
            "/search",
            {
                "q": zip5,
                "format": "json",
                "addressdetails": "1",
                "countrycodes": "us",
                "limit": "6",
            },
        )
        items = fallback if isinstance(fallback, list) else []

    # Nominatim's forward postalcode boundary often omits the municipality name;
    # reverse-geocoding the centroid recovers the city/town for the ZIP.
    first_with_coords = next(
        (item for item in items if isinstance(item, dict) and item.get("lat") and item.get("lon")),
        None,
    )
    if first_with_coords is not None:
        first_addr = first_with_coords.get("address") or {}
        if not _extract_municipality(first_addr):
            try:
                rev = await _throttled_get(
                    "/reverse",
                    {
                        "lat": str(first_with_coords["lat"]),
                        "lon": str(first_with_coords["lon"]),
                        "format": "json",
                        "addressdetails": "1",
                    },
                )
                rev_items = rev if isinstance(rev, list) else ([rev] if isinstance(rev, dict) else [])
                items = [*rev_items, *items]
            except Exception as rev_exc:  # noqa: BLE001 — reverse enrichment is best-effort
                logger.debug("Best-effort reverse geocode for ZIP {} failed: {}", zip5, rev_exc)

    return items, zip5


@router.get("/places", response_model=PlacesResponse)
async def feed_places(
    q: str = Query("", description="Free-text place or 5-digit US ZIP query (min 3 chars)."),
) -> PlacesResponse:
    """Place typeahead backed by the Nominatim proxy — real hits only.

    Maps each geocoder result to a clean {name, city, county, state,
    state_code, postal_code, latitude, longitude}. Short/empty queries (<3 chars)
    return an empty result set; no fabricated/placeholder suggestions (CLAUDE.md).
    """
    query = (q or "").strip()
    if len(query) < 3:
        return PlacesResponse(results=[])

    with tracer.start_as_current_span("feed.places") as span:
        span.set_attribute("feed.places.q_len", len(query))
        try:
            items, zip5 = await _fetch_nominatim_candidates(query)
        except HTTPException:
            raise
        except Exception as exc:  # noqa: BLE001
            span.record_exception(exc)
            logger.error("Place typeahead failed for '{}': {}", query, exc)
            raise HTTPException(status_code=502, detail="Geocoder error.")

        results: List[PlaceHit] = []
        seen_places: set[tuple[str, str, str]] = set()
        for item in items:
            if not isinstance(item, dict):
                continue
            address = item.get("address") or {}
            city = _extract_municipality(address)
            county = address.get("county")
            state_code = _derive_state_code(address)
            state = address.get("state") or (_STATE_CODE_TO_NAME.get(state_code) if state_code else None)
            postal_code = address.get("postcode") or zip5
            try:
                lat = float(item["lat"])
                lon = float(item["lon"])
            except (KeyError, TypeError, ValueError):
                continue  # no usable coordinates -> skip (no fabricated geo)

            dedupe_key = (
                (city or "").strip().lower(),
                (county or "").strip().lower(),
                (state_code or "").strip().upper(),
            )
            if any(dedupe_key):
                if dedupe_key in seen_places:
                    continue
                seen_places.add(dedupe_key)

            results.append(PlaceHit(
                name=item.get("display_name") or city or query,
                city=city,
                county=county,
                state=state,
                state_code=state_code,
                postal_code=postal_code,
                latitude=lat,
                longitude=lon,
            ))

        span.set_attribute("feed.places.hits", len(results))
        return PlacesResponse(results=results)