File size: 45,770 Bytes
35fc7ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
"""Same-origin JSON API for the local Amazon Home Services service marketplace."""

from __future__ import annotations

import hashlib
import json
import os
import re
import secrets
import sqlite3
import uuid

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-amazon-home-services-session"


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


async def json_object(request: Request) -> dict:
    """Treat an empty or malformed JSON request as an empty object.

    The generated Harbor action corpus intentionally probes mutation endpoints
    without a body.  Those requests are client errors, not server faults, so
    route-level validation must produce the same deterministic 4xx response as
    an empty object instead of leaking Starlette's JSONDecodeError as a 500.
    """
    try:
        body = await request.json()
    except (json.JSONDecodeError, UnicodeDecodeError):
        return {}
    return body if isinstance(body, dict) else {}


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 require_role(c: Ctx, role: str) -> JSONResponse | None:
    if (response := require(c)) is not None:
        return response
    if c.profile["role"] != role:
        return error(403, "forbidden", f"This action requires the {role} role.")
    return None


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()),
    )
    connection.execute(
        "INSERT OR IGNORE INTO ahs_settings(account_id,updated_at) VALUES (?,?)",
        (account_id, db.now()),
    )


def create_profile_subject(connection, registration) -> str:
    account_id = str(registration["account_id"])
    ensure_profile(
        connection,
        account_id=account_id,
        email=str(registration["email"]),
        name=str(registration["display_name"]),
    )
    return account_id


@router.post("/__websitebench__/session")
def diagnostic_session(request: Request):
    expected = os.environ.get("WEBSITEBENCH_DIAGNOSTIC_FIXTURE_TOKEN", "")
    supplied = request.headers.get("x-websitebench-fixture-token", "")
    if (
        os.environ.get("WEBSITEBENCH_DIAGNOSTIC_FIXTURES") != "1"
        or not expected
        or not secrets.compare_digest(expected, supplied)
    ):
        return error(404, "not-found", "Not found.")

    browser_token, _ = SERVICES.auth.ensure_session(
        request.cookies.get(_cookie(request))
    )
    email = "diagnostic-owner@amazon-home-services.invalid"
    supplied_code = request.headers.get("x-websitebench-mailbox-code", "")
    if not supplied_code:
        SERVICES.auth.start_registration(
            browser_token,
            email=email,
            display_name="Diagnostic Homeowner",
            password="DiagnosticOnly!2026",
            restart_invalid_flow=True,
        )
        response = JSONResponse(
            {"ok": True, "pending": True, "recipient": email}, status_code=202
        )
        set_cookie(response, request, browser_token)
        return response
    SERVICES.auth.verify_registration_code(browser_token, supplied_code)
    result = SERVICES.auth.complete_registration(
        browser_token,
        subject_factory=create_profile_subject,
    )
    account = result["account"]
    with SERVICES.auth.connect() as connection:
        connection.execute(
            "UPDATE an_profiles SET role='provider' WHERE account_id=?",
            (account["account_id"],),
        )
        connection.execute(
            """INSERT OR IGNORE INTO an_projects(
                project_id, account_id, service_slug, title, status, current_step,
                created_at, updated_at
            ) VALUES (?,?,?,?,?,?,?,?)""",
            (
                "diagnostic-project",
                account["account_id"],
                "tv-wall-mounting",
                "Diagnostic TV mounting project",
                "draft",
                1,
                db.now(),
                db.now(),
            ),
        )
    response = JSONResponse({"ok": True, "fixture": "diagnostic-owner"})
    set_cookie(response, request, result["session_token"])
    return response


@router.post("/auth/signup")
async def signup(request: Request, c: Ctx = Depends(ctx)):
    body = await json_object(request)
    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, "delivery_status": mail["status"]} if mail else error(404, "not-found", "No delivery status is available.")


@router.post("/auth/verify")
async def verify(request: Request, c: Ctx = Depends(ctx)):
    body = await json_object(request)
    try:
        c.auth.verify_registration_code(c.token, str(body.get("code", "")))
        result = c.auth.complete_registration(
            c.token,
            subject_factory=create_profile_subject,
        )
    except AuthError as exc:
        return error(400, "invalid", str(exc))
    account = result["account"]
    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 json_object(request)
    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 json_object(request)
    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 json_object(request)
    try:
        c.auth.verify_password_reset_code(c.token, str(body.get("code", "")))
        rotated = c.auth.complete_password_reset(
            c.token,
            new_password=str(body.get("password", "")),
        )
    except AuthError as exc:
        return error(400, "invalid", str(exc))
    response = JSONResponse({"ok": True})
    set_cookie(response, request, rotated)
    return response


@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}
    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("/settings")
def settings(c: Ctx = Depends(ctx)):
    if (response := require(c)) is not None:
        return response
    with c.connect() as connection:
        connection.execute("INSERT OR IGNORE INTO ahs_settings(account_id,updated_at) VALUES (?,?)", (c.account_id, db.now()))
        item = db.row(connection.execute("SELECT * FROM ahs_settings WHERE account_id=?", (c.account_id,)).fetchone())
        current_digest = c.auth.session_owner_digest(c.token)
        sessions = db.rows(connection.execute(
            "SELECT session_digest,created_at FROM local_auth_sessions WHERE account_id=? AND revoked_at IS NULL AND expires_at>? ORDER BY created_at DESC,session_digest",
            (c.account_id, db.now()),
        ).fetchall())
    return {"settings": item, "sessions": [
        {"id": row["session_digest"][:12], "label": item["session_label"], "current": row["session_digest"] == current_digest, "last_seen": "Now" if row["session_digest"] == current_digest else "Earlier local sign-in"}
        for row in sessions
    ]}


@router.post("/settings")
async def update_settings(request: Request, c: Ctx = Depends(ctx)):
    if (response := require(c)) is not None:
        return response
    body = await request.json()
    values = [1 if body.get(key) else 0 for key in ["analytics", "personalized", "email_updates", "sms_updates", "reminders"]]
    with c.connect() as connection:
        connection.execute("INSERT OR IGNORE INTO ahs_settings(account_id,updated_at) VALUES (?,?)", (c.account_id, db.now()))
        connection.execute("UPDATE ahs_settings SET analytics=?,personalized=?,email_updates=?,sms_updates=?,reminders=?,updated_at=? WHERE account_id=?", (*values, db.now(), c.account_id))
    return {"ok": True, "stored": True}


@router.post("/sessions/revoke")
def revoke_other_sessions(c: Ctx = Depends(ctx)):
    if (response := require(c)) is not None:
        return response
    current_digest = c.auth.session_owner_digest(c.token)
    with c.connect() as connection:
        cursor = connection.execute(
            "UPDATE local_auth_sessions SET revoked_at=? WHERE account_id=? AND session_digest<>? AND revoked_at IS NULL",
            (db.now(), c.account_id, current_digest),
        )
    revoked = cursor.rowcount
    return {"ok": True, "revoked": revoked, "message": f"Revoked {revoked} other local session{'s' if revoked != 1 else ''}."}


@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:
        # A toggle is one read-modify-write transaction, including concurrent clicks.
        connection.execute("BEGIN IMMEDIATE")
        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", "tv-wall-mounting"))
    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())
        item["shares"] = db.rows(connection.execute("SELECT * FROM ahs_shares WHERE project_id=? ORDER BY created_at DESC", (project_id,)).fetchall())
        hired = connection.execute("SELECT name FROM an_providers WHERE provider_id=?", (item.get("hired_provider_id"),)).fetchone()
        item["technician"] = {"name": "Alex M.", "team": hired["name"] if hired else "Assignment pending", "vehicle": "Local demo van 14", "eta": "25–35 minutes"} if hired else None
    return {"project": item}


@router.post("/projects/{project_id}/share")
async def share_project(project_id: str, request: Request, c: Ctx = Depends(ctx)):
    if (response := require(c)) is not None:
        return response
    body = await request.json()
    recipient = str(body.get("recipient", "")).strip().lower()
    permission = str(body.get("permission", "view"))
    if not re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", recipient) or permission not in {"view", "manage"}:
        return error(422, "validation", "Enter a valid local recipient and permission.")
    with c.connect() as connection:
        if not _project(connection, project_id, c.account_id):
            return error(404, "not-found", "Project not found.")
        share_id = db.new_id("shr")
        connection.execute("INSERT INTO ahs_shares VALUES (?,?,?,?,?,?,?)", (share_id, project_id, c.account_id, recipient, permission, 1, db.now()))
        _event(connection, project_id, "share-enabled", f"Local {permission} access enabled for {recipient}")
    return {"ok": True, "share_id": share_id, "recipient": recipient, "permission": permission, "local_only": True}


@router.post("/shares/{share_id}/toggle")
def toggle_share(share_id: str, c: Ctx = Depends(ctx)):
    if (response := require(c)) is not None:
        return response
    with c.connect() as connection:
        row = connection.execute("SELECT * FROM ahs_shares WHERE share_id=? AND account_id=?", (share_id, c.account_id)).fetchone()
        if not row:
            return error(404, "not-found", "Local share not found.")
        enabled = 0 if row["enabled"] else 1
        connection.execute("UPDATE ahs_shares SET enabled=? WHERE share_id=?", (enabled, share_id))
    return {"ok": True, "enabled": bool(enabled)}


@router.post("/waitlist")
async def join_waitlist(request: Request, c: Ctx = Depends(ctx)):
    if (response := require(c)) is not None:
        return response
    body = await request.json()
    service = str(body.get("service", "tv-wall-mounting"))
    zip_code = str(body.get("zip", ""))
    date = str(body.get("preferred_date", ""))
    if not re.fullmatch(r"\d{5}", zip_code) or not date:
        return error(422, "validation", "Choose a date and five-digit ZIP.")
    with c.connect() as connection:
        waitlist_id = db.new_id("wait")
        connection.execute("INSERT INTO ahs_waitlist VALUES (?,?,?,?,?,?,?)", (waitlist_id, c.account_id, service, zip_code, date, "waiting-local", db.now()))
    return {"ok": True, "waitlist_id": waitlist_id, "status": "waiting-local", "external_notification": False}


@router.post("/projects/{project_id}/reminder")
def reminder(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.")
        if project["status"] not in {"booked", "rescheduled"}:
            return error(409, "not-eligible", "Only an active local booking can enable a reminder.")
        _event(connection, project_id, "reminder-enabled", "Local appointment reminder enabled")
    return {"ok": True, "channel": "local-notification"}


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


@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 str(body.get("issue", "")).startswith("mount") or str(body.get("tv_size", "")):
            problems = [p for p in problems if p["field"] not in {"property_type", "budget"}]
            for key in ["tv_size", "package", "wall_type", "equipment"]:
                if not str(body.get(key, "")).strip():
                    problems.append({"field": key, "message": "This field is required for a size-matched installation."})
        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":
        if not str(body.get("date", "")).strip() or not str(body.get("time_window", "")).strip():
            problems.append({"field": "date", "message": "Choose a date and time window."})
    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:
        project = _project(connection, project_id, c.account_id)
        if not project:
            return error(404, "not-found", "Project not found.")
        if project["status"] != "draft":
            return error(409, "locked", "Submitted requests cannot be edited here.")
        connection.execute(f"UPDATE an_projects SET {column}=?,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:
        project = _project(connection, project_id, c.account_id)
        if not project:
            return error(404, "not-found", "Project not found.")
        if project["status"] != "draft":
            return error(409, "locked", "Only a draft request can be matched.")
        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"])
        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 __import__("json").loads(p["availability_json"])]
        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 = {"tv-wall-mounting": 17900, "furniture-assembly": 13900, "appliance-installation": 24900, "plumbing": 58000, "electrical": 72000, "heating-cooling": 125000, "interior-painting": 180000, "roofing": 460000, "house-cleaning": 22000, "landscaping": 125000, "handyman": 32000}.get(project["service_slug"], 75000)
        scope = db.loads(project["scope_json"])
        size_multiplier = {"small": 0.82, "medium": 1.0, "large": 1.28, "extra-large": 1.5}.get(scope.get("tv_size"), 1.0)
        package_add = {"standard": 0, "concealed-cable": 4500, "premium-soundbar": 8500}.get(scope.get("package"), 0)
        for index, provider in enumerate(sorted(providers, key=lambda p: (-p["rating"], p["response_minutes"]))[:4]):
            amount = int(base * size_multiplier * (0.9 + index * 0.13 + provider["price_level"] * 0.04)) + package_add
            available = __import__("json").loads(provider["availability_json"])[0]
            connection.execute("INSERT INTO an_quotes VALUES (?,?,?,?,?,?,?,?,?,?)", (db.new_id("quo"), project_id, provider["provider_id"], amount, max(2500, int(amount * 0.2)), 1 + index, available, "Size-matched mounting hardware, labor and selected local package included.", "offered", db.now()))
        code = "AHS-" + 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)
        if not project:
            return error(404, "not-found", "Quote not found.")
        if project["status"] != "matched":
            return error(409, "not-eligible", "Only a matched request can select a provider.")
        quote = connection.execute("SELECT * FROM an_quotes WHERE quote_id=? AND project_id=?", (quote_id, project_id)).fetchone()
        if 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"amazon-home-services:{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), None
    except PaymentError as exc:
        return None, "invalid", str(exc), None
    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.", None
    return (
        intent["flow_id"],
        "approved",
        "Approved only inside the local payment sandbox.",
        {
            "owner": owner,
            "amount_minor": amount + tip,
            "currency": "USD",
            "fingerprint": fingerprint,
        },
    )


@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.")
    if kind not in {"deposit", "final"} or tip < 0 or tip > 100000:
        return error(422, "validation", "Payment amount or tip is invalid.")
    if kind == "deposit" and tip:
        return error(422, "validation", "Tips are available only with final payment.")
    expected_status = "awaiting_deposit" if kind == "deposit" else "work_completed"
    with c.connect() as connection:
        project = _project(connection, project_id, c.account_id)
        if not project:
            return error(404, "not-found", "Project not found.")
        if project["status"] != expected_status:
            return error(
                409,
                "stale-checkout",
                f"{kind.title()} payment is not available for this project state.",
            )
        amount = project["deposit_cents"] if kind == "deposit" else project["final_cents"]
    if amount <= 0:
        return error(422, "validation", "Payment amount or tip is invalid.")
    flow_id, outcome, message, approval = _pay(c, project, scenario, kind, amount, tip)
    if outcome == "approved":
        status = "booked" if kind == "deposit" else "paid_complete"
        try:
            with c.backend.lifecycle.connection(transaction=True) as connection:
                current = _project(connection, project_id, c.account_id)
                if not current:
                    return error(404, "not-found", "Project not found.")
                if current["status"] != expected_status:
                    return error(
                        409,
                        "stale-checkout",
                        f"{kind.title()} payment is no longer available.",
                    )
                c.backend.payments.consume_approval(
                    connection,
                    flow_id=flow_id,
                    owner=approval["owner"],
                    amount_minor=approval["amount_minor"],
                    currency=approval["currency"],
                    fingerprint=approval["fingerprint"],
                )
                connection.execute(
                    "INSERT INTO an_payments VALUES (?,?,?,?,?,?,?,?)",
                    (db.new_id("pay"), project_id, kind, scenario, amount, tip, outcome, db.now()),
                )
                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")
        except sqlite3.DatabaseError:
            return error(500, "payment-not-persisted", "The local approval was not consumed because the booking update could not be persisted.")
    else:
        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":
        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_role(c, "provider")) 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' ORDER BY p.updated_at DESC").fetchall())
    return {"provider": "HomeTech Certified Installers", "leads": items}


@router.post("/provider/leads/{project_id}")
async def update_lead(project_id: str, request: Request, c: Ctx = Depends(ctx)):
    if (response := require_role(c, "provider")) 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 WHERE project_id=? AND provider_id='pro-brightpipe'", (project_id,)).fetchone()
        if not quote:
            return error(404, "not-found", "Lead not found.")
        _event(connection, project_id, "provider-update", f"HomeTech changed local job status to {status}")
    return {"ok": True, "status": status}