File size: 34,567 Bytes
366d6fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Same-origin JSON API for the local Angi service marketplace."""

from __future__ import annotations

import hashlib
from datetime import date, datetime
import re
import secrets
import sqlite3
import uuid
from typing import Any

from fastapi import APIRouter, Depends, Request, Response
from fastapi.responses import JSONResponse

from websitebench.local_clone_auth import store as auth_store_mod
from websitebench.site_backend.errors import PaymentError, PaymentRejected

from . import db
from .services import SERVICES

AuthError = auth_store_mod.AuthError
AuthConflict = auth_store_mod.AuthConflict
AuthValidationError = auth_store_mod.AuthValidationError
router = APIRouter(prefix="/api")
LOCAL_COOKIE = "websitebench-angi-session"


def error(status: int, code: str, message: str, **extra) -> JSONResponse:
    return JSONResponse({"error": {"code": code, "message": message}, **extra}, status_code=status)


def _secure(request: Request) -> bool:
    return request.url.scheme == "https" or request.headers.get("x-forwarded-proto", "").lower() == "https"


def _cookie(request: Request) -> str:
    return SERVICES.cookie_name if _secure(request) else LOCAL_COOKIE


class Ctx:
    def __init__(self, request: Request) -> None:
        self.request = request
        self.services = SERVICES
        self.auth = SERVICES.auth
        self.backend = SERVICES.backend
        self.token = request.cookies.get(_cookie(request))
        self.session = self.auth.resolve_session(self.token)
        account = (self.session or {}).get("account") or {}
        self.account_id = account.get("account_id")
        self.profile = None
        if self.account_id:
            with self.connect() as connection:
                self.profile = db.row(connection.execute("SELECT * FROM an_profiles WHERE account_id=?", (self.account_id,)).fetchone())

    def connect(self) -> sqlite3.Connection:
        return self.auth.connect()


def ctx(request: Request) -> Ctx:
    return Ctx(request)


def require(c: Ctx) -> JSONResponse | None:
    return None if c.account_id and c.profile else error(401, "unauthorized", "Sign in to continue.")


def set_cookie(response: Response, request: Request, token: str) -> None:
    response.set_cookie(_cookie(request), token, httponly=True, secure=_secure(request), samesite="lax", path="/")


def ensure_profile(connection, *, account_id: str, email: str, name: str) -> None:
    connection.execute(
        "INSERT OR IGNORE INTO an_profiles(account_id,email,display_name,created_at) VALUES (?,?,?,?)",
        (account_id, email, name, db.now()),
    )


@router.post("/auth/signup")
async def signup(request: Request, c: Ctx = Depends(ctx)):
    body = await request.json()
    token, _ = c.auth.ensure_session(c.token)
    try:
        result = c.auth.start_registration(token, email=str(body.get("email", "")), display_name=str(body.get("name", "")), password=str(body.get("password", "")), restart_invalid_flow=True)
    except AuthConflict as exc:
        return error(409, "conflict", str(exc))
    except (AuthValidationError, AuthError) as exc:
        return error(400, "invalid", str(exc))
    response = JSONResponse({"ok": True, "pending_id": result["pending_id"], "mail_status": result["mail_status"]})
    set_cookie(response, request, token)
    return response


@router.get("/auth/mail")
def local_mail(purpose: str, c: Ctx = Depends(ctx)):
    if not c.token:
        return error(401, "unauthorized", "No local session.")
    try:
        mail = c.auth.local_mail_for_session(c.token, purpose=purpose)
    except ValueError:
        return error(400, "invalid", "Unknown mail purpose.")
    return {"purpose": purpose, "template": mail["template"], "verification_code": mail["verification_code"]} if mail else error(404, "not-found", "No local mail is available.")


@router.post("/auth/verify")
async def verify(request: Request, c: Ctx = Depends(ctx)):
    body = await request.json()
    try:
        c.auth.verify_registration_code(c.token, str(body.get("code", "")))
        result = c.auth.complete_registration(c.token)
    except AuthError as exc:
        return error(400, "invalid", str(exc))
    account = result["account"]
    with c.connect() as connection:
        ensure_profile(connection, account_id=account["account_id"], email=account["email_normalized"], name=account["display_name"])
    response = JSONResponse({"ok": True, "account": account})
    set_cookie(response, request, result["session_token"])
    return response


@router.post("/auth/login")
async def login(request: Request, c: Ctx = Depends(ctx)):
    body = await request.json()
    token, _ = c.auth.ensure_session(c.token)
    try:
        result = c.auth.sign_in(token, email=str(body.get("email", "")), password=str(body.get("password", "")))
    except AuthError:
        return error(401, "bad-credentials", "The email or password is incorrect.")
    account = result["account"]
    with c.connect() as connection:
        ensure_profile(connection, account_id=account["account_id"], email=account["email_normalized"], name=account["display_name"])
    response = JSONResponse({"ok": True, "account": account})
    set_cookie(response, request, result["session_token"])
    return response


@router.post("/auth/logout")
def logout(request: Request, c: Ctx = Depends(ctx)):
    c.auth.sign_out(c.token)
    response = JSONResponse({"ok": True})
    response.delete_cookie(_cookie(request), path="/")
    response.delete_cookie(SERVICES.cookie_name, path="/")
    return response


@router.post("/auth/forgot")
async def forgot(request: Request, c: Ctx = Depends(ctx)):
    body = await request.json()
    token, _ = c.auth.ensure_session(c.token)
    try:
        c.auth.start_password_reset(token, email=str(body.get("email", "")), restart_invalid_flow=True)
    except AuthError as exc:
        return error(400, "invalid", str(exc))
    response = JSONResponse({"ok": True})
    set_cookie(response, request, token)
    return response


@router.post("/auth/reset")
async def reset(request: Request, c: Ctx = Depends(ctx)):
    body = await request.json()
    try:
        c.auth.verify_password_reset_code(c.token, str(body.get("code", "")))
        c.auth.complete_password_reset(c.token, new_password=str(body.get("password", "")))
    except AuthError as exc:
        return error(400, "invalid", str(exc))
    return {"ok": True}


@router.get("/me")
def me(c: Ctx = Depends(ctx)):
    if (response := require(c)) is not None:
        return response
    with c.connect() as connection:
        projects = connection.execute("SELECT COUNT(*) n FROM an_projects WHERE account_id=?", (c.account_id,)).fetchone()["n"]
        favorites = connection.execute("SELECT COUNT(*) n FROM an_favorites WHERE account_id=?", (c.account_id,)).fetchone()["n"]
    return {"profile": c.profile, "projects": projects, "favorites": favorites}


@router.post("/profile")
async def profile(request: Request, c: Ctx = Depends(ctx)):
    if (response := require(c)) is not None:
        return response
    body = await request.json()
    allowed = ["display_name", "phone", "address1", "city", "state", "zip", "role"]
    fields = {key: str(body[key]).strip() for key in allowed if key in body}
    for key in ("newsletter_email", "newsletter_sms"):
        if key in body:
            fields[key] = 1 if body[key] else 0
    if "zip" in fields and fields["zip"] and not re.fullmatch(r"\d{5}", fields["zip"]):
        return error(400, "invalid", "ZIP code must contain five digits.")
    if fields.get("role") not in {None, "homeowner", "provider"}:
        return error(400, "invalid", "Choose homeowner or provider mode.")
    if not fields:
        return error(400, "invalid", "Nothing to update.")
    with c.connect() as connection:
        connection.execute(f"UPDATE an_profiles SET {', '.join(k+'=?' for k in fields)} WHERE account_id=?", (*fields.values(), c.account_id))
    return {"ok": True}


@router.get("/providers")
def providers(service: str = "", zip: str = "", verified: bool = False, rating: float = 0, price: int = 0, sort: str = "recommended"):
    with SERVICES.auth.connect() as connection:
        items = db.rows(connection.execute("SELECT * FROM an_providers").fetchall())
    for item in items:
        item["services"] = __import__("json").loads(item["services_json"])
        item["availability"] = __import__("json").loads(item["availability_json"])
        item["distance"] = db.distance(zip, item["zip"]) if zip else 0
    if service:
        items = [item for item in items if service in item["services"]]
    if zip:
        items = [item for item in items if item["distance"] <= item["radius_miles"]]
    if verified:
        items = [item for item in items if item["verified"]]
    if rating:
        items = [item for item in items if item["rating"] >= rating]
    if price:
        items = [item for item in items if item["price_level"] <= price]
    keys = {"rating": lambda x: -x["rating"], "reviews": lambda x: -x["review_count"], "distance": lambda x: x["distance"], "price": lambda x: x["price_level"]}
    items.sort(key=keys.get(sort, lambda x: (-x["verified"], -x["rating"], x["response_minutes"])))
    return {"providers": items}


@router.post("/favorites/{provider_id}")
def favorite(provider_id: str, c: Ctx = Depends(ctx)):
    if (response := require(c)) is not None:
        return response
    with c.connect() as connection:
        provider = connection.execute("SELECT provider_id FROM an_providers WHERE provider_id=? OR slug=?", (provider_id, provider_id)).fetchone()
        if not provider:
            return error(404, "not-found", "Provider not found.")
        provider_id = provider["provider_id"]
        found = connection.execute("SELECT 1 FROM an_favorites WHERE account_id=? AND provider_id=?", (c.account_id, provider_id)).fetchone()
        if found:
            connection.execute("DELETE FROM an_favorites WHERE account_id=? AND provider_id=?", (c.account_id, provider_id))
        else:
            connection.execute("INSERT INTO an_favorites VALUES (?,?,?)", (c.account_id, provider_id, db.now()))
    return {"ok": True, "favorited": not bool(found)}


@router.get("/favorites")
def favorites(c: Ctx = Depends(ctx)):
    if (response := require(c)) is not None:
        return response
    with c.connect() as connection:
        items = db.rows(connection.execute("SELECT p.* FROM an_favorites f JOIN an_providers p ON p.provider_id=f.provider_id WHERE f.account_id=? ORDER BY f.created_at DESC", (c.account_id,)).fetchall())
    return {"favorites": items}


@router.post("/estimates")
async def estimate(request: Request, c: Ctx = Depends(ctx)):
    if (response := require(c)) is not None:
        return response
    body = await request.json()
    service = str(body.get("service", ""))
    size = str(body.get("size", ""))
    urgency = str(body.get("urgency", "standard"))
    zip_code = str(body.get("zip", ""))
    if size not in {"small", "medium", "large"} or not re.fullmatch(r"\d{5}", zip_code):
        return error(422, "validation", "Choose a project size and valid five-digit ZIP.")
    with c.connect() as connection:
        row = connection.execute("SELECT * FROM an_services WHERE slug=?", (service,)).fetchone()
        if not row:
            return error(404, "not-found", "Service not found.")
        multiplier = {"small": 0.75, "medium": 1.0, "large": 1.6}[size] * (1.25 if urgency == "urgent" else 1)
        low, high = int(row["price_low"] * multiplier), int(row["price_high"] * multiplier)
        estimate_id = db.new_id("est")
        connection.execute("INSERT INTO an_estimates VALUES (?,?,?,?,?,?,?,?,?)", (estimate_id, c.account_id, service, size, urgency, zip_code, low, high, db.now()))
    return {"ok": True, "estimate_id": estimate_id, "low_cents": low, "high_cents": high, "unit": row["unit"]}


def _project(connection, project_id: str, account_id: str):
    return connection.execute("SELECT * FROM an_projects WHERE project_id=? AND account_id=?", (project_id, account_id)).fetchone()


def _event(connection, project_id: str, kind: str, label: str) -> None:
    connection.execute("INSERT INTO an_events VALUES (?,?,?,?,?)", (db.new_id("evt"), project_id, kind, label, db.now()))


@router.post("/projects")
async def create_project(request: Request, c: Ctx = Depends(ctx)):
    if (response := require(c)) is not None:
        return response
    body = await request.json()
    service = str(body.get("service", "plumbing"))
    with c.connect() as connection:
        svc = connection.execute("SELECT name FROM an_services WHERE slug=?", (service,)).fetchone()
        if not svc:
            return error(404, "not-found", "Service not found.")
        project_id = db.new_id("prj")
        now = db.now()
        connection.execute("INSERT INTO an_projects(project_id,account_id,service_slug,title,created_at,updated_at) VALUES (?,?,?,?,?,?)", (project_id, c.account_id, service, f"{svc['name']} home project", now, now))
        _event(connection, project_id, "draft-created", "Local project request started")
    return {"ok": True, "project_id": project_id}


@router.get("/projects")
def project_list(c: Ctx = Depends(ctx)):
    if (response := require(c)) is not None:
        return response
    with c.connect() as connection:
        items = db.rows(connection.execute("SELECT * FROM an_projects WHERE account_id=? ORDER BY updated_at DESC", (c.account_id,)).fetchall())
    return {"projects": items}


@router.get("/projects/{project_id}")
def project_detail(project_id: str, c: Ctx = Depends(ctx)):
    if (response := require(c)) is not None:
        return response
    with c.connect() as connection:
        project = _project(connection, project_id, c.account_id)
        if not project:
            return error(404, "not-found", "Project not found.")
        item = dict(project)
        item["scope"] = db.loads(item["scope_json"])
        item["location"] = db.loads(item["location_json"])
        item["schedule"] = db.loads(item["schedule_json"])
        item["events"] = db.rows(connection.execute("SELECT kind,label,created_at FROM an_events WHERE project_id=? ORDER BY created_at", (project_id,)).fetchall())
        item["quotes"] = db.rows(connection.execute("SELECT q.*,p.name provider_name,p.slug provider_slug,p.rating FROM an_quotes q JOIN an_providers p ON p.provider_id=q.provider_id WHERE q.project_id=? ORDER BY amount_cents", (project_id,)).fetchall())
        item["messages"] = db.rows(connection.execute("SELECT m.*,p.name provider_name FROM an_messages m JOIN an_providers p ON p.provider_id=m.provider_id WHERE m.project_id=? ORDER BY m.created_at", (project_id,)).fetchall())
        item["payments"] = db.rows(connection.execute("SELECT * FROM an_payments WHERE project_id=? ORDER BY created_at", (project_id,)).fetchall())
    return {"project": item}


VALID_STEPS = {"scope", "location", "schedule"}


def schedule_problems(schedule):
    problems = []
    value = schedule.get("date", "")
    try:
        valid = isinstance(value, str) and date.fromisoformat(value).isoformat() == value
    except (ValueError, TypeError):
        valid = False
    if not valid:
        problems.append({"field": "date", "message": "Choose a valid date (YYYY-MM-DD)."})
    for key, choices in [("time_window", {"morning", "afternoon", "evening"}), ("flexibility", {"exact", "week", "any"})]:
        if schedule.get(key) not in choices:
            problems.append({"field": key, "message": "Choose one of the available options."})
    return problems


def matching_slots(provider, schedule):
    preferred = date.fromisoformat(schedule["date"])
    start, end = {"morning": (8, 12), "afternoon": (12, 16), "evening": (16, 19)}[schedule["time_window"]]
    result = []
    for slot in __import__("json").loads(provider["availability_json"]):
        when = datetime.strptime(slot, "%Y-%m-%d %H:%M")
        delta = (when.date() - preferred).days
        allowed = delta == 0 if schedule["flexibility"] == "exact" else 0 <= delta <= 7 if schedule["flexibility"] == "week" else delta >= 0
        if allowed and start <= when.hour < end:
            result.append(slot)
    return sorted(result)



@router.put("/projects/{project_id}/steps/{step}")
async def save_project_step(project_id: str, step: str, request: Request, c: Ctx = Depends(ctx)):
    if (response := require(c)) is not None:
        return response
    if step not in VALID_STEPS:
        return error(404, "not-found", "Unknown request step.")
    body = await request.json()
    problems = []
    if step == "scope":
        for key in ["issue", "description", "property_type", "budget"]:
            if not str(body.get(key, "")).strip():
                problems.append({"field": key, "message": "This field is required."})
        if body.get("issue") == "other" and len(str(body.get("description", ""))) < 15:
            problems.append({"field": "description", "message": "Add at least 15 characters for an other request."})
    if step == "location":
        for key in ["address1", "city", "state", "zip"]:
            if not str(body.get(key, "")).strip():
                problems.append({"field": key, "message": "This field is required."})
        if body.get("zip") and not re.fullmatch(r"\d{5}", str(body["zip"])):
            problems.append({"field": "zip", "message": "Enter a five-digit ZIP."})
    if step == "schedule":
        problems.extend(schedule_problems(body))
    if problems:
        return JSONResponse({"ok": False, "problems": problems}, status_code=422)
    column = {"scope": "scope_json", "location": "location_json", "schedule": "schedule_json"}[step]
    index = {"scope": 2, "location": 3, "schedule": 4}[step]
    with c.connect() as connection:
        connection.execute("BEGIN IMMEDIATE")
        project = _project(connection, project_id, c.account_id)
        if not project:
            return error(404, "not-found", "Project not found.")
        if project["status"] not in {"draft", "no_match"}:
            return error(409, "locked", "Submitted requests cannot be edited here.")
        connection.execute(f"UPDATE an_projects SET {column}=?,status='draft',current_step=?,updated_at=? WHERE project_id=?", (db.dumps(body), max(project["current_step"], index), db.now(), project_id))
    return {"ok": True, "next_step": index}


@router.post("/projects/{project_id}/match")
def match_project(project_id: str, c: Ctx = Depends(ctx)):
    if (response := require(c)) is not None:
        return response
    with c.connect() as connection:
        connection.execute("BEGIN IMMEDIATE")
        project = _project(connection, project_id, c.account_id)
        if not project:
            return error(404, "not-found", "Project not found.")
        if project["status"] not in {"draft", "no_match"}:
            return error(409, "locked", "This request has already been submitted.")
        missing = [name for name, col in [("scope", "scope_json"), ("location", "location_json"), ("schedule", "schedule_json")] if not db.loads(project[col])]
        if missing:
            return error(422, "incomplete", "Complete scope, location and schedule before matching.", incomplete_steps=missing)
        location = db.loads(project["location_json"])
        schedule = db.loads(project["schedule_json"])
        if problems := schedule_problems(schedule):
            return JSONResponse({"ok": False, "problems": problems}, status_code=422)
        providers = db.rows(connection.execute("SELECT * FROM an_providers").fetchall())
        providers = [p for p in providers if project["service_slug"] in __import__("json").loads(p["services_json"]) and db.distance(location["zip"], p["zip"]) <= p["radius_miles"] and matching_slots(p, schedule)]
        if not providers:
            connection.execute("UPDATE an_projects SET status='no_match',updated_at=? WHERE project_id=?", (db.now(), project_id))
            _event(connection, project_id, "no-match", "No provider is available for the selected area and schedule")
            return {"ok": True, "matched": 0, "status": "no_match"}
        connection.execute("DELETE FROM an_quotes WHERE project_id=?", (project_id,))
        base = {"plumbing": 58000, "electrical": 72000, "heating-cooling": 125000, "interior-painting": 180000, "roofing": 460000, "house-cleaning": 22000, "landscaping": 125000, "handyman": 32000}.get(project["service_slug"], 75000)
        for index, provider in enumerate(sorted(providers, key=lambda p: (-p["rating"], p["response_minutes"]))[:4]):
            amount = int(base * (0.9 + index * 0.13 + provider["price_level"] * 0.04))
            available = matching_slots(provider, schedule)[0]
            connection.execute("INSERT INTO an_quotes VALUES (?,?,?,?,?,?,?,?,?,?)", (db.new_id("quo"), project_id, provider["provider_id"], amount, max(5000, int(amount * 0.2)), 1 + index, available, "Synthetic local quote with labor and standard materials included.", "offered", db.now()))
        code = "ANG-" + secrets.token_hex(3).upper()
        connection.execute("UPDATE an_projects SET status='matched',confirmation_code=?,current_step=5,updated_at=? WHERE project_id=?", (code, db.now(), project_id))
        _event(connection, project_id, "matched", f"{min(4, len(providers))} local demo quotes prepared")
    return {"ok": True, "matched": min(4, len(providers)), "status": "matched", "confirmation_code": code}


@router.post("/projects/{project_id}/messages")
async def message_provider(project_id: str, request: Request, c: Ctx = Depends(ctx)):
    if (response := require(c)) is not None:
        return response
    body = await request.json()
    text = str(body.get("body", "")).strip()
    provider_id = str(body.get("provider_id", ""))
    if not text or len(text) > 2000:
        return error(422, "validation", "Enter a message up to 2,000 characters.")
    with c.connect() as connection:
        project = _project(connection, project_id, c.account_id)
        quote = connection.execute("SELECT 1 FROM an_quotes WHERE project_id=? AND provider_id=?", (project_id, provider_id)).fetchone()
        if not project or not quote:
            return error(404, "not-found", "Matched provider not found.")
        connection.execute("INSERT INTO an_messages VALUES (?,?,?,?,?,?)", (db.new_id("msg"), project_id, provider_id, "homeowner", text, db.now()))
        connection.execute("INSERT INTO an_messages VALUES (?,?,?,?,?,?)", (db.new_id("msg"), project_id, provider_id, "provider", "Thanks — I noted that on your local demo quote and can answer here.", db.now() + 1))
    return {"ok": True}


@router.post("/projects/{project_id}/hire")
async def hire(project_id: str, request: Request, c: Ctx = Depends(ctx)):
    if (response := require(c)) is not None:
        return response
    body = await request.json()
    quote_id = str(body.get("quote_id", ""))
    with c.connect() as connection:
        project = _project(connection, project_id, c.account_id)
        quote = connection.execute("SELECT * FROM an_quotes WHERE quote_id=? AND project_id=?", (quote_id, project_id)).fetchone()
        if not project or not quote:
            return error(404, "not-found", "Quote not found.")
        connection.execute("UPDATE an_quotes SET status=CASE WHEN quote_id=? THEN 'selected' ELSE 'not-selected' END WHERE project_id=?", (quote_id, project_id))
        connection.execute("UPDATE an_projects SET status='awaiting_deposit',selected_quote_id=?,hired_provider_id=?,appointment_at=?,deposit_cents=?,final_cents=?,updated_at=? WHERE project_id=?", (quote_id, quote["provider_id"], quote["available_at"], quote["deposit_cents"], quote["amount_cents"] - quote["deposit_cents"], db.now(), project_id))
        _event(connection, project_id, "provider-selected", "Provider and appointment selected; local deposit pending")
    return {"ok": True, "status": "awaiting_deposit", "deposit_cents": quote["deposit_cents"]}


def _pay(c: Ctx, project, scenario: str, kind: str, amount: int, tip: int = 0):
    owner = f"angi:{kind}:{c.account_id}:{project['project_id']}"
    fingerprint = hashlib.sha256(f"{owner}:{amount}:{tip}".encode()).hexdigest()
    try:
        intent = c.backend.payments.create_intent(owner=owner, amount_minor=amount + tip, currency="USD", fingerprint=fingerprint, idempotency_key=f"intent-{uuid.uuid4().hex}")
        attempt = c.backend.payments.attempt(flow_id=intent["flow_id"], owner=owner, amount_minor=amount + tip, currency="USD", fingerprint=fingerprint, scenario_id=scenario, idempotency_key=f"attempt-{uuid.uuid4().hex}")
    except PaymentRejected as exc:
        return None, "declined", str(exc)
    except PaymentError as exc:
        return None, "invalid", str(exc)
    outcome = str(attempt.get("status") or attempt.get("outcome") or "").upper()
    if outcome != "APPROVED":
        return None, outcome.lower(), "The simulated payment did not complete. Your project state is preserved."
    with c.backend.lifecycle.connection(transaction=True) as connection:
        c.backend.payments.consume_approval(connection, flow_id=intent["flow_id"], owner=owner, amount_minor=amount + tip, currency="USD", fingerprint=fingerprint)
    return intent["flow_id"], "approved", "Approved only inside the local payment sandbox."


@router.post("/projects/{project_id}/payment")
async def payment(project_id: str, request: Request, c: Ctx = Depends(ctx)):
    if (response := require(c)) is not None:
        return response
    body = await request.json()
    kind = str(body.get("kind", "deposit"))
    scenario = str(body.get("scenario", "sandbox-approved"))
    try:
        tip = int(body.get("tip_cents", 0) or 0)
    except (TypeError, ValueError):
        return error(422, "validation", "Payment amount or tip is invalid.")
    with c.connect() as connection:
        project = _project(connection, project_id, c.account_id)
        if not project:
            return error(404, "not-found", "Project not found.")
        amount = project["deposit_cents"] if kind == "deposit" else project["final_cents"]
    if kind not in {"deposit", "final"} or amount <= 0 or tip < 0 or tip > 100000:
        return error(422, "validation", "Payment amount or tip is invalid.")
    flow_id, outcome, message = _pay(c, project, scenario, kind, amount, tip)
    with c.connect() as connection:
        connection.execute("INSERT INTO an_payments VALUES (?,?,?,?,?,?,?,?)", (db.new_id("pay"), project_id, kind, scenario, amount, tip, outcome, db.now()))
        if outcome == "approved":
            status = "booked" if kind == "deposit" else "paid_complete"
            connection.execute("UPDATE an_projects SET status=?,updated_at=? WHERE project_id=?", (status, db.now(), project_id))
            _event(connection, project_id, f"{kind}-approved", f"{kind.title()} approved in local sandbox; no real charge")
    if outcome != "approved":
        return JSONResponse({"ok": False, "outcome": outcome, "message": message}, status_code=402)
    return {"ok": True, "outcome": outcome, "status": "booked" if kind == "deposit" else "paid_complete", "flow_id": flow_id}


@router.post("/projects/{project_id}/reschedule")
async def reschedule(project_id: str, request: Request, c: Ctx = Depends(ctx)):
    body = await request.json()
    appointment = str(body.get("appointment_at", ""))
    if (response := require(c)) is not None:
        return response
    if not appointment:
        return error(422, "validation", "Choose an available appointment.")
    with c.connect() as connection:
        project = _project(connection, project_id, c.account_id)
        if not project or project["status"] not in {"booked", "rescheduled"}:
            return error(409, "not-eligible", "Only an active local booking can be rescheduled.")
        connection.execute("UPDATE an_projects SET status='rescheduled',appointment_at=?,updated_at=? WHERE project_id=?", (appointment, db.now(), project_id))
        _event(connection, project_id, "rescheduled", f"Appointment moved to {appointment}")
    return {"ok": True, "status": "rescheduled", "appointment_at": appointment}


@router.post("/projects/{project_id}/cancel")
async def cancel(project_id: str, request: Request, c: Ctx = Depends(ctx)):
    body = await request.json()
    reason = str(body.get("reason", "")).strip()
    if (response := require(c)) is not None:
        return response
    if not reason:
        return error(422, "validation", "Choose a cancellation reason.")
    with c.connect() as connection:
        project = _project(connection, project_id, c.account_id)
        if not project or project["status"] not in {"booked", "rescheduled"}:
            return error(409, "not-eligible", "This project is not eligible for cancellation.")
        refund = project["deposit_cents"]
        connection.execute("UPDATE an_projects SET status='cancelled_refunded',refund_cents=?,updated_at=? WHERE project_id=?", (refund, db.now(), project_id))
        _event(connection, project_id, "cancelled", f"Local booking cancelled; simulated refund eligibility ${refund / 100:.2f}")
    return {"ok": True, "status": "cancelled_refunded", "refund_cents": refund, "confirmation": "REF-" + secrets.token_hex(3).upper()}


@router.post("/projects/{project_id}/complete")
def complete(project_id: str, c: Ctx = Depends(ctx)):
    if (response := require(c)) is not None:
        return response
    with c.connect() as connection:
        project = _project(connection, project_id, c.account_id)
        if not project or project["status"] not in {"booked", "rescheduled"}:
            return error(409, "not-eligible", "Only an active booking can be marked complete.")
        connection.execute("UPDATE an_projects SET status='work_completed',updated_at=? WHERE project_id=?", (db.now(), project_id))
        _event(connection, project_id, "work-completed", "Homeowner approved synthetic project completion")
    return {"ok": True, "status": "work_completed"}


@router.post("/projects/{project_id}/review")
async def review(project_id: str, request: Request, c: Ctx = Depends(ctx)):
    if (response := require(c)) is not None:
        return response
    body = await request.json()
    service_type = str(body.get("service_type", "")).strip()
    text = str(body.get("body", "")).strip()
    try:
        rating = int(body.get("rating", 0))
    except (TypeError, ValueError):
        rating = 0
    if rating not in range(1, 6) or not service_type or not 3 <= len(text) <= 1000:
        return error(422, "validation", "Choose 1-5 stars, a service type and review text.")
    with c.connect() as connection:
        project = _project(connection, project_id, c.account_id)
        if not project or not project["hired_provider_id"] or project["status"] not in {"work_completed", "paid_complete", "reviewed"}:
            return error(409, "not-eligible", "Complete the local project before reviewing.")
        existing = connection.execute("SELECT review_id FROM an_public_reviews WHERE account_id=? AND provider_id=? AND service_type=?", (c.account_id, project["hired_provider_id"], service_type)).fetchone()
        if existing:
            connection.execute("UPDATE an_public_reviews SET rating=?,body=?,public=?,created_at=? WHERE review_id=?", (rating, text, 1 if body.get("public", True) else 0, db.now(), existing["review_id"]))
            review_id = existing["review_id"]
        else:
            review_id = db.new_id("rev")
            connection.execute("INSERT INTO an_public_reviews VALUES (?,?,?,?,?,?,?,?,?)", (review_id, project["hired_provider_id"], c.account_id, c.profile["display_name"], service_type, rating, text, 1 if body.get("public", True) else 0, db.now()))
        connection.execute("UPDATE an_projects SET status='reviewed',updated_at=? WHERE project_id=?", (db.now(), project_id))
        _event(connection, project_id, "reviewed", f"{rating}-star {service_type} review saved locally")
    return {"ok": True, "review_id": review_id, "rating": rating, "service_type": service_type, "body": text, "public": bool(body.get("public", True))}


@router.post("/projects/{project_id}/support")
async def support(project_id: str, request: Request, c: Ctx = Depends(ctx)):
    if (response := require(c)) is not None:
        return response
    body = await request.json()
    reason, details = str(body.get("reason", "")).strip(), str(body.get("details", "")).strip()
    if not reason or len(details) < 10:
        return error(422, "validation", "Choose a reason and add at least 10 characters.")
    with c.connect() as connection:
        if not _project(connection, project_id, c.account_id):
            return error(404, "not-found", "Project not found.")
        case_id = "SUP-" + secrets.token_hex(3).upper()
        connection.execute("INSERT INTO an_support VALUES (?,?,?,?,?,?,?)", (case_id, project_id, c.account_id, reason, details, "open-local", db.now()))
        _event(connection, project_id, "support-opened", f"Local support case {case_id} opened")
    return {"ok": True, "case_id": case_id, "status": "open-local"}


@router.get("/provider/leads")
def provider_leads(c: Ctx = Depends(ctx)):
    if (response := require(c)) is not None:
        return response
    with c.connect() as connection:
        items = db.rows(connection.execute("SELECT p.project_id,p.title,p.status,p.appointment_at,p.updated_at,q.amount_cents,q.status quote_status FROM an_projects p JOIN an_quotes q ON q.project_id=p.project_id WHERE q.provider_id='pro-brightpipe' AND p.account_id=? ORDER BY p.updated_at DESC", (c.account_id,)).fetchall())
    return {"provider": "Bright Pipe Plumbing", "leads": items}


@router.post("/provider/leads/{project_id}")
async def update_lead(project_id: str, request: Request, c: Ctx = Depends(ctx)):
    if (response := require(c)) is not None:
        return response
    body = await request.json()
    status = str(body.get("status", ""))
    if status not in {"accepted", "scheduled", "in-progress", "completed-local"}:
        return error(422, "validation", "Choose a valid local job status.")
    with c.connect() as connection:
        quote = connection.execute("SELECT 1 FROM an_quotes q JOIN an_projects p ON p.project_id=q.project_id WHERE q.project_id=? AND q.provider_id='pro-brightpipe' AND p.account_id=?", (project_id, c.account_id)).fetchone()
        if not quote:
            return error(404, "not-found", "Lead not found.")
        _event(connection, project_id, "provider-update", f"Bright Pipe changed local job status to {status}")
    return {"ok": True, "status": status}