"""Trips store: SQLite always; PocketBase preferred SoT when reachable.""" from __future__ import annotations import time import uuid from datetime import date from typing import Any from . import geo_pb from .geo_cities import ( city_public, get_seed_city, list_seed_cities, resolve_city_id, ) from .geo_h3 import latlng_to_cell from .store import db def _uid() -> str: return f"trip_{uuid.uuid4().hex[:12]}" def _now() -> str: return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime()) def ensure_trips_schema() -> None: with db() as conn: conn.executescript( """ CREATE TABLE IF NOT EXISTS trips ( id TEXT PRIMARY KEY, guest_id TEXT NOT NULL, city_id TEXT, city TEXT NOT NULL, country TEXT, lat REAL, lng REAL, h3_cell TEXT, arrival_date TEXT, departure_date TEXT, visibility TEXT NOT NULL DEFAULT 'public', status TEXT NOT NULL DEFAULT 'planned', updated_at TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_trips_guest ON trips(guest_id); CREATE INDEX IF NOT EXISTS idx_trips_city ON trips(city_id); CREATE INDEX IF NOT EXISTS idx_trips_vis ON trips(visibility, status); """ ) def _row_trip(r: Any) -> dict[str, Any]: return { "id": r["id"], "guest_id": r["guest_id"], "city_id": r["city_id"] or "", "city": r["city"], "country": r["country"] or "", "lat": r["lat"], "lng": r["lng"], "h3_cell": r["h3_cell"] or "", "arrival_date": r["arrival_date"] or "", "departure_date": r["departure_date"] or "", "visibility": r["visibility"] or "public", "status": r["status"] or "planned", "updated_at": r["updated_at"], } def list_trips_sqlite( *, guest_id: str | None = None, city_id: str | None = None, visibility: str | None = None, status: str | None = None, limit: int = 200, ) -> list[dict[str, Any]]: ensure_trips_schema() clauses: list[str] = [] args: list[Any] = [] if guest_id: clauses.append("guest_id = ?") args.append(guest_id) if city_id: clauses.append("city_id = ?") args.append(city_id) if visibility: clauses.append("visibility = ?") args.append(visibility) if status: clauses.append("status = ?") args.append(status) where = (" WHERE " + " AND ".join(clauses)) if clauses else "" sql = f"SELECT * FROM trips{where} ORDER BY updated_at DESC LIMIT ?" args.append(max(1, min(limit, 500))) with db() as conn: rows = conn.execute(sql, args).fetchall() return [_row_trip(r) for r in rows] def list_trips(**kwargs: Any) -> list[dict[str, Any]]: pb = geo_pb.list_trips(**kwargs) if pb is not None: return pb return list_trips_sqlite(**kwargs) def save_trip_sqlite(trip: dict[str, Any]) -> dict[str, Any]: ensure_trips_schema() with db() as conn: conn.execute( """ INSERT INTO trips ( id, guest_id, city_id, city, country, lat, lng, h3_cell, arrival_date, departure_date, visibility, status, updated_at ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET city_id=excluded.city_id, city=excluded.city, country=excluded.country, lat=excluded.lat, lng=excluded.lng, h3_cell=excluded.h3_cell, arrival_date=excluded.arrival_date, departure_date=excluded.departure_date, visibility=excluded.visibility, status=excluded.status, updated_at=excluded.updated_at """, ( trip["id"], trip["guest_id"], trip.get("city_id") or "", trip["city"], trip.get("country") or "", trip.get("lat"), trip.get("lng"), trip.get("h3_cell") or "", trip.get("arrival_date") or "", trip.get("departure_date") or "", trip.get("visibility") or "public", trip.get("status") or "planned", trip.get("updated_at") or _now(), ), ) return trip def create_trip(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]: city = (payload.get("city") or "").strip() if not city: raise ValueError("city required") city_id = (payload.get("city_id") or "").strip() or resolve_city_id(city) or "" seed = get_seed_city(city_id) if city_id else None lat = payload.get("lat") lng = payload.get("lng") if lat is None and seed: lat = seed["lat"] if lng is None and seed: lng = seed["lng"] country = (payload.get("country") or "").strip() or (seed or {}).get("country") or "" h3_cell = "" if lat is not None and lng is not None: h3_cell = latlng_to_cell(float(lat), float(lng)) trip = { "id": _uid(), "guest_id": guest_id, "city_id": city_id, "city": city, "country": country, "lat": float(lat) if lat is not None else None, "lng": float(lng) if lng is not None else None, "h3_cell": h3_cell, "arrival_date": (payload.get("arrival_date") or "").strip()[:10], "departure_date": (payload.get("departure_date") or "").strip()[:10], "visibility": (payload.get("visibility") or "public").strip() or "public", "status": (payload.get("status") or "planned").strip() or "planned", "updated_at": _now(), } if trip["visibility"] not in {"public", "friends", "private"}: trip["visibility"] = "public" if trip["status"] not in {"here", "planned", "past"}: trip["status"] = "planned" pb = geo_pb.upsert_trip(trip) if pb: # keep local mirror with PB id trip = pb save_trip_sqlite(trip) return trip def update_trip(guest_id: str, trip_id: str, payload: dict[str, Any]) -> dict[str, Any] | None: existing = None for t in list_trips(guest_id=guest_id, visibility=None, limit=500): if t["id"] == trip_id: existing = t break if not existing: # try sqlite only rows = list_trips_sqlite(guest_id=guest_id, visibility=None, limit=500) existing = next((t for t in rows if t["id"] == trip_id), None) if not existing: return None city = (payload.get("city") or existing["city"]).strip() city_id = (payload.get("city_id") if "city_id" in payload else existing.get("city_id")) or "" city_id = str(city_id).strip() or resolve_city_id(city) or "" seed = get_seed_city(city_id) if city_id else None lat = payload.get("lat", existing.get("lat")) lng = payload.get("lng", existing.get("lng")) if lat is None and seed: lat = seed["lat"] if lng is None and seed: lng = seed["lng"] trip = { **existing, "city": city, "city_id": city_id, "country": (payload.get("country") if "country" in payload else existing.get("country")) or (seed or {}).get("country") or "", "lat": float(lat) if lat is not None else None, "lng": float(lng) if lng is not None else None, "arrival_date": ( payload.get("arrival_date") if "arrival_date" in payload else existing.get("arrival_date") ) or "", "departure_date": ( payload.get("departure_date") if "departure_date" in payload else existing.get("departure_date") ) or "", "visibility": ( payload.get("visibility") if "visibility" in payload else existing.get("visibility") ) or "public", "status": (payload.get("status") if "status" in payload else existing.get("status")) or "planned", "updated_at": _now(), } if trip["lat"] is not None and trip["lng"] is not None: trip["h3_cell"] = latlng_to_cell(float(trip["lat"]), float(trip["lng"])) pb = geo_pb.upsert_trip(trip) if pb: trip = pb save_trip_sqlite(trip) return trip def delete_trip(guest_id: str, trip_id: str) -> bool: pb = geo_pb.delete_trip(trip_id, guest_id) ensure_trips_schema() with db() as conn: cur = conn.execute( "DELETE FROM trips WHERE id = ? AND guest_id = ?", (trip_id, guest_id), ) local = cur.rowcount > 0 if pb is True: return True if pb is False and not local: return False return local or pb is not False def map_cities() -> list[dict[str, Any]]: """City aggregation for map — seed counts + live trip overlays (no personal coords).""" trips = list_trips(visibility="public", limit=500) live_by_city: dict[str, dict[str, int]] = {} for t in trips: cid = t.get("city_id") or resolve_city_id(t.get("city") or "") or "" if not cid: continue bucket = live_by_city.setdefault(cid, {"here": 0, "planned": 0}) st = t.get("status") or "planned" if st == "here": bucket["here"] += 1 elif st == "planned": bucket["planned"] += 1 out = [] for c in list_seed_cities(): live = live_by_city.get(c["id"], {}) extras = { "arrivingSoon": int(live.get("planned") or 0), "currentlyHere": int(live.get("here") or 0), "h3": latlng_to_cell(c["lat"], c["lng"]), # bump seed memberCount with live presence signal (display only) "memberCount": int(c.get("members") or 0) + int(live.get("here") or 0), } out.append(city_public(c, extras=extras)) return out def city_detail(city_id: str) -> dict[str, Any] | None: seed = get_seed_city(city_id) if not seed: return None trips = list_trips(city_id=city_id, visibility="public", limit=200) here = [t for t in trips if t.get("status") == "here"] planned = [t for t in trips if t.get("status") == "planned"] base = city_public( seed, extras={ "currentlyHere": len(here), "arrivingSoon": len(planned), "h3": latlng_to_cell(seed["lat"], seed["lng"]), "memberCount": int(seed.get("members") or 0) + len(here), }, ) base["recentArrivals"] = [ { "guestId": t["guest_id"][:8] + "…", "city": t["city"], "status": t["status"], "arrival_date": t.get("arrival_date") or "", "departure_date": t.get("departure_date") or "", } for t in (here + planned)[:12] ] return base def _parse_ymd(s: str) -> date | None: s = (s or "").strip()[:10] if len(s) < 10: return None try: return date.fromisoformat(s) except ValueError: return None def travel_overlaps(guest_id: str) -> list[dict[str, Any]]: mine = list_trips(guest_id=guest_id, visibility=None, limit=100) mine = [t for t in mine if t.get("visibility") != "private"] others = [ t for t in list_trips(visibility="public", limit=500) if t.get("guest_id") != guest_id ] out: list[dict[str, Any]] = [] for a in mine: a0, a1 = _parse_ymd(a.get("arrival_date") or ""), _parse_ymd(a.get("departure_date") or "") if not a0 or not a1 or a1 < a0: continue for b in others: if (a.get("city_id") and b.get("city_id") and a["city_id"] != b["city_id"]) or ( not a.get("city_id") and (a.get("city") or "").split("·")[0].strip() != (b.get("city") or "").split("·")[0].strip() ): continue b0, b1 = _parse_ymd(b.get("arrival_date") or ""), _parse_ymd( b.get("departure_date") or "" ) if not b0 or not b1 or b1 < b0: continue start = max(a0, b0) end = min(a1, b1) if end < start: continue days = (end - start).days + 1 out.append( { "city": a.get("city") or b.get("city"), "cityId": a.get("city_id") or b.get("city_id") or "", "overlapDays": days, "from": start.isoformat(), "to": end.isoformat(), "otherGuest": (b.get("guest_id") or "")[:8] + "…", "myTripId": a["id"], "theirStatus": b.get("status") or "", } ) out.sort(key=lambda x: (-int(x["overlapDays"]), x["from"])) return out[:50]