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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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
# Copyright (c) 2026 CrewHub. All rights reserved.
# Proprietary and confidential. See LICENSE for details.
"""Admin-only endpoints for platform governance.

All endpoints require authentication and is_admin=True on the user record.
Includes: platform stats, user/agent management, credit grants, re-embedding.
"""

from uuid import UUID

from fastapi import APIRouter, Depends, HTTPException, Query, Request
from pydantic import BaseModel, Field
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload

from src.core.audit import audit_log
from src.core.auth import get_current_user
from src.core.rate_limiter import rate_limit_by_ip
from src.database import get_db
from src.models.agent import Agent
from src.models.task import Task
from src.models.transaction import Transaction
from src.models.user import User
from src.schemas.agent import AgentResponse, AgentStatus, VerificationLevel
from src.schemas.auth import UserResponse
from src.schemas.task import TaskResponse, TaskListResponse
from src.schemas.credits import TransactionListResponse, TransactionResponse
from src.schemas.channel import ChannelResponse

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


# ---------------------------------------------------------------------------
# Bootstrap: promote caller to admin when no admins exist yet
# ---------------------------------------------------------------------------


@router.post("/bootstrap", dependencies=[Depends(rate_limit_by_ip)])
async def bootstrap_admin(
    request: Request,
    current_user: dict = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    """One-time self-promotion to admin β€” only works when no admins exist."""
    admin_count = (
        await db.execute(select(func.count()).where(User.is_admin.is_(True)))
    ).scalar_one()
    if admin_count > 0:
        raise HTTPException(status_code=403, detail="Admin already exists")

    firebase_uid = current_user.get("firebase_uid")
    if firebase_uid:
        result = await db.execute(
            select(User).where(User.firebase_uid == firebase_uid)
        )
    else:
        result = await db.execute(
            select(User).where(User.id == UUID(current_user["id"]))
        )
    user = result.scalar_one_or_none()
    if user is None:
        raise HTTPException(status_code=401, detail="User not found")
    user.is_admin = True
    user.admin_role = "super_admin"
    await audit_log(db, action="admin.bootstrap", actor_user_id=str(user.id), target_type="user", target_id=user.id, new_value={"is_admin": True, "admin_role": "super_admin"}, request=request)
    await db.flush()
    return {"message": f"{user.email} is now admin"}


# ---------------------------------------------------------------------------
# Admin guard dependency
# ---------------------------------------------------------------------------


async def require_admin(
    current_user: dict = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
) -> User:
    """Dependency that verifies the current user is an admin."""
    firebase_uid = current_user.get("firebase_uid")
    if firebase_uid:
        result = await db.execute(
            select(User).where(User.firebase_uid == firebase_uid)
        )
    else:
        result = await db.execute(
            select(User).where(User.id == UUID(current_user["id"]))
        )

    user = result.scalar_one_or_none()
    if user is None:
        raise HTTPException(status_code=401, detail="User not found")
    if not user.is_admin:
        raise HTTPException(status_code=403, detail="Admin access required")
    return user


async def require_super_admin(admin: User = Depends(require_admin)) -> User:
    """Require super_admin role. Used for user management and role changes."""
    if admin.admin_role != "super_admin":
        raise HTTPException(status_code=403, detail="Requires super_admin role")
    return admin


async def require_ops_or_super(admin: User = Depends(require_admin)) -> User:
    """Require ops_admin or super_admin role. Used for agent/submission management."""
    if admin.admin_role not in ("super_admin", "ops_admin"):
        raise HTTPException(status_code=403, detail="Requires ops_admin or super_admin role")
    return admin


async def require_billing_or_super(admin: User = Depends(require_admin)) -> User:
    """Require billing_admin or super_admin role. Used for credits/transactions."""
    if admin.admin_role not in ("super_admin", "billing_admin"):
        raise HTTPException(status_code=403, detail="Requires billing_admin or super_admin role")
    return admin


# ---------------------------------------------------------------------------
# Agent Submissions β€” review queue
# ---------------------------------------------------------------------------


@router.get("/submissions", tags=["admin"])
async def list_pending_submissions(
    status: str = Query("pending_review"),
    page: int = Query(1, ge=1),
    per_page: int = Query(20, ge=1, le=100),
    admin: "User" = Depends(require_ops_or_super),
    db: AsyncSession = Depends(get_db),
):
    """List agent submissions for review."""
    from src.models.submission import AgentSubmission
    from src.schemas.submission import SubmissionResponse

    total_q = select(func.count()).select_from(
        select(AgentSubmission).where(AgentSubmission.status == status).subquery()
    )
    total = (await db.execute(total_q)).scalar_one()

    stmt = (
        select(AgentSubmission)
        .where(AgentSubmission.status == status)
        .order_by(AgentSubmission.created_at.asc())
        .offset((page - 1) * per_page)
        .limit(per_page)
    )
    result = await db.execute(stmt)
    submissions = result.scalars().all()

    return {
        "submissions": [SubmissionResponse.model_validate(s) for s in submissions],
        "total": total,
    }


@router.post("/submissions/{submission_id}/approve", tags=["admin"])
async def approve_submission(
    submission_id: UUID,
    request: Request,
    admin: "User" = Depends(require_ops_or_super),
    db: AsyncSession = Depends(get_db),
):
    """Approve a submission β€” registers it as a marketplace agent."""
    from datetime import datetime, timezone
    from src.models.submission import AgentSubmission

    submission = await db.get(AgentSubmission, submission_id)
    if not submission:
        raise HTTPException(status_code=404, detail="Submission not found")
    if submission.status != "pending_review":
        raise HTTPException(status_code=400, detail=f"Cannot approve: status is {submission.status}")

    # Create agent record with Langflow proxy endpoint
    import os
    import re
    proxy_base = os.getenv("LANGFLOW_PROXY_BASE", "https://api.crewhubai.com")
    endpoint = f"{proxy_base}/langflow/run/{submission.langflow_flow_id}"

    agent = Agent(
        owner_id=submission.user_id,
        name=submission.name,
        description=submission.description or "",
        endpoint=endpoint,
        category=submission.category or "general",
        tags=submission.tags or [],
        pricing={"model": "per_task", "credits": submission.credits, "license_type": "commercial"},
        status="active",
    )
    db.add(agent)
    await db.flush()

    # Auto-generate primary skill with embedding for discoverability
    try:
        from src.models.skill import AgentSkill
        from src.core.embeddings import EmbeddingService

        skill_key = re.sub(r"[^a-z0-9-]", "-", submission.name.lower()).strip("-")[:50]
        skill_desc = submission.description or f"A {submission.category or 'general'} agent built with CrewHub Builder"
        skill_text = f"{submission.name}: {skill_desc}"

        embed_svc = EmbeddingService()
        embedding = await embed_svc.generate(skill_text)

        skill = AgentSkill(
            agent_id=agent.id,
            skill_key=skill_key or "default",
            name=submission.name,
            description=skill_desc,
            input_modes=["text"],
            output_modes=["text"],
            examples=[],
            embedding=embedding,
        )
        db.add(skill)
        await db.flush()
    except Exception as _skill_err:
        import logging
        logging.getLogger(__name__).warning("Skill creation failed during approval: %s", _skill_err)

    # Update submission
    submission.status = "approved"
    submission.reviewed_by = admin.id
    submission.reviewed_at = datetime.now(timezone.utc)
    submission.agent_id = agent.id

    await audit_log(db, action="admin.approve_submission", actor_user_id=str(admin.id), target_type="submission", target_id=submission_id, new_value={"agent_id": str(agent.id)}, request=request)
    await db.commit()
    return {"status": "approved", "agent_id": str(agent.id), "submission_id": str(submission_id)}


@router.post("/submissions/{submission_id}/reject", tags=["admin"])
async def reject_submission(
    submission_id: UUID,
    request: Request,
    admin: "User" = Depends(require_ops_or_super),
    db: AsyncSession = Depends(get_db),
    notes: str = Query(..., min_length=1, description="Reason for rejection"),
):
    """Reject a submission with reviewer notes."""
    from datetime import datetime, timezone
    from src.models.submission import AgentSubmission

    submission = await db.get(AgentSubmission, submission_id)
    if not submission:
        raise HTTPException(status_code=404, detail="Submission not found")
    if submission.status != "pending_review":
        raise HTTPException(status_code=400, detail=f"Cannot reject: status is {submission.status}")

    submission.status = "rejected"
    submission.reviewer_notes = notes
    submission.reviewed_by = admin.id
    submission.reviewed_at = datetime.now(timezone.utc)

    await audit_log(db, action="admin.reject_submission", actor_user_id=str(admin.id), target_type="submission", target_id=submission_id, new_value={"notes": notes}, request=request)
    await db.commit()
    return {"status": "rejected", "submission_id": str(submission_id)}


@router.post("/submissions/{submission_id}/revoke", tags=["admin"])
async def revoke_submission(
    submission_id: UUID,
    request: Request,
    admin: "User" = Depends(require_ops_or_super),
    db: AsyncSession = Depends(get_db),
):
    """Revoke a previously approved submission β€” takes agent offline."""
    from datetime import datetime, timezone
    from src.models.submission import AgentSubmission

    submission = await db.get(AgentSubmission, submission_id)
    if not submission:
        raise HTTPException(status_code=404, detail="Submission not found")
    if submission.status != "approved":
        raise HTTPException(status_code=400, detail=f"Cannot revoke: status is {submission.status}")

    # Deactivate the agent
    if submission.agent_id:
        agent = await db.get(Agent, submission.agent_id)
        if agent:
            agent.status = "inactive"

    submission.status = "revoked"
    submission.reviewed_at = datetime.now(timezone.utc)

    await audit_log(db, action="admin.revoke_submission", actor_user_id=str(admin.id), target_type="submission", target_id=submission_id, request=request)
    await db.commit()
    return {"status": "revoked", "submission_id": str(submission_id)}


# ---------------------------------------------------------------------------
# Bulk pricing update
# ---------------------------------------------------------------------------


class PricingUpdate(BaseModel):
    agent_id: UUID
    credits: float = Field(ge=0)


class BulkPricingRequest(BaseModel):
    updates: list[PricingUpdate]


@router.post("/bulk-pricing", tags=["admin"])
async def bulk_update_pricing(
    data: BulkPricingRequest,
    request: Request,
    admin: "User" = Depends(require_ops_or_super),
    db: AsyncSession = Depends(get_db),
):
    """Update pricing for multiple agents at once. Admin only."""
    results = []
    for update in data.updates:
        agent = await db.get(Agent, update.agent_id)
        if not agent:
            results.append({"id": str(update.agent_id), "status": "not_found"})
            continue
        pricing = agent.pricing or {}
        old = pricing.get("credits", 0)
        pricing["credits"] = update.credits
        agent.pricing = pricing
        from sqlalchemy.orm.attributes import flag_modified
        flag_modified(agent, "pricing")
        results.append({
            "id": str(update.agent_id),
            "name": agent.name,
            "old_credits": old,
            "new_credits": update.credits,
            "status": "updated",
        })
    await audit_log(db, action="admin.bulk_pricing", actor_user_id=str(admin.id), target_type="agents", new_value={"count": len(data.updates)}, request=request)
    await db.commit()
    return {"updated": len([r for r in results if r["status"] == "updated"]), "results": results}


# ---------------------------------------------------------------------------
# Platform stats
# ---------------------------------------------------------------------------


class PlatformStats(BaseModel):
    total_users: int
    active_users: int
    total_agents: int
    active_agents: int
    total_tasks: int
    completed_tasks: int
    failed_tasks: int
    total_transaction_volume: float


@router.get("/stats", response_model=PlatformStats)
async def get_platform_stats(
    admin: User = Depends(require_admin),
    db: AsyncSession = Depends(get_db),
) -> PlatformStats:
    """Aggregated platform KPIs."""
    total_users = (await db.execute(select(func.count(User.id)))).scalar_one()
    active_users = (
        await db.execute(select(func.count(User.id)).where(User.is_active.is_(True)))
    ).scalar_one()

    total_agents = (await db.execute(select(func.count(Agent.id)))).scalar_one()
    active_agents = (
        await db.execute(
            select(func.count(Agent.id)).where(Agent.status == "active")
        )
    ).scalar_one()

    total_tasks = (await db.execute(select(func.count(Task.id)))).scalar_one()
    completed_tasks = (
        await db.execute(
            select(func.count(Task.id)).where(Task.status == "completed")
        )
    ).scalar_one()
    failed_tasks = (
        await db.execute(
            select(func.count(Task.id)).where(Task.status == "failed")
        )
    ).scalar_one()

    vol_result = await db.execute(select(func.coalesce(func.sum(Transaction.amount), 0)))
    total_volume = float(vol_result.scalar_one())

    return PlatformStats(
        total_users=total_users,
        active_users=active_users,
        total_agents=total_agents,
        active_agents=active_agents,
        total_tasks=total_tasks,
        completed_tasks=completed_tasks,
        failed_tasks=failed_tasks,
        total_transaction_volume=total_volume,
    )


# ---------------------------------------------------------------------------
# User management
# ---------------------------------------------------------------------------


class AdminUserListResponse(BaseModel):
    users: list[UserResponse]
    total: int


@router.get("/users/", response_model=AdminUserListResponse)
async def list_users(
    page: int = Query(1, ge=1),
    per_page: int = Query(20, ge=1, le=100),
    admin: User = Depends(require_super_admin),
    db: AsyncSession = Depends(get_db),
) -> AdminUserListResponse:
    """List all platform users (admin only)."""
    total = (await db.execute(select(func.count(User.id)))).scalar_one()
    offset = (page - 1) * per_page
    result = await db.execute(
        select(User).order_by(User.created_at.desc()).offset(offset).limit(per_page)
    )
    users = [UserResponse.model_validate(u) for u in result.scalars().all()]
    return AdminUserListResponse(users=users, total=total)


class UserStatusUpdate(BaseModel):
    is_active: bool | None = None
    is_admin: bool | None = None
    account_tier: str | None = None  # "free" or "premium"


@router.put("/users/{user_id}/status", response_model=UserResponse)
async def update_user_status(
    user_id: UUID,
    data: UserStatusUpdate,
    request: Request,
    admin: User = Depends(require_super_admin),
    db: AsyncSession = Depends(get_db),
) -> UserResponse:
    """Activate/deactivate a user, grant/revoke admin, or set account tier (admin only)."""
    result = await db.execute(select(User).where(User.id == user_id))
    user = result.scalar_one_or_none()
    if user is None:
        raise HTTPException(status_code=404, detail="User not found")
    await audit_log(db, action="admin.update_user_status", actor_user_id=str(admin.id), target_type="user", target_id=user_id, old_value={"is_active": user.is_active, "is_admin": user.is_admin}, new_value=data.model_dump(exclude_none=True), request=request)
    if data.is_active is not None:
        user.is_active = data.is_active
    if data.is_admin is not None:
        user.is_admin = data.is_admin
    if data.account_tier is not None:
        if data.account_tier not in ("free", "premium"):
            raise HTTPException(status_code=400, detail="account_tier must be 'free' or 'premium'")
        user.account_tier = data.account_tier
    await db.flush()
    return UserResponse.model_validate(user)


VALID_ADMIN_ROLES = ("super_admin", "ops_admin", "billing_admin")


class AdminRoleUpdate(BaseModel):
    admin_role: str = Field(..., description="One of: super_admin, ops_admin, billing_admin")


@router.put("/users/{user_id}/role", response_model=UserResponse)
async def update_user_role(
    user_id: UUID,
    data: AdminRoleUpdate,
    request: Request,
    admin: User = Depends(require_super_admin),
    db: AsyncSession = Depends(get_db),
) -> UserResponse:
    """Change an admin's role or demote to non-admin (super_admin only).

    Set admin_role to a valid role to change it, or "none" to revoke admin access.
    Only super_admins can change roles. Cannot change your own role.
    """
    if data.admin_role != "none" and data.admin_role not in VALID_ADMIN_ROLES:
        raise HTTPException(
            status_code=400,
            detail=f"admin_role must be one of: {', '.join(VALID_ADMIN_ROLES)}, or 'none' to demote",
        )

    result = await db.execute(select(User).where(User.id == user_id))
    user = result.scalar_one_or_none()
    if user is None:
        raise HTTPException(status_code=404, detail="User not found")

    # Cannot change your own role (prevent self-demotion lockout)
    if user.id == admin.id:
        raise HTTPException(status_code=403, detail="Cannot change your own role. Ask another super_admin.")

    old_role = {"is_admin": user.is_admin, "admin_role": user.admin_role}

    if data.admin_role == "none":
        # Demote: revoke admin access entirely
        user.is_admin = False
        user.admin_role = None
    else:
        # Promote or change role
        user.is_admin = True
        user.admin_role = data.admin_role

    await audit_log(
        db, action="admin.update_user_role", actor_user_id=str(admin.id),
        target_type="user", target_id=user_id,
        old_value=old_role,
        new_value={"is_admin": user.is_admin, "admin_role": user.admin_role},
        request=request,
    )
    await db.flush()
    return UserResponse.model_validate(user)


# ---------------------------------------------------------------------------
# All tasks (not user-scoped)
# ---------------------------------------------------------------------------


@router.get("/tasks/", response_model=TaskListResponse)
async def list_all_tasks(
    page: int = Query(1, ge=1),
    per_page: int = Query(20, ge=1, le=100),
    status: str | None = Query(None),
    admin: User = Depends(require_billing_or_super),
    db: AsyncSession = Depends(get_db),
) -> TaskListResponse:
    """List all tasks across the platform (admin only)."""
    query = select(Task)
    if status:
        query = query.where(Task.status == status)

    total = (
        await db.execute(select(func.count()).select_from(query.subquery()))
    ).scalar_one()

    offset = (page - 1) * per_page
    result = await db.execute(
        query.order_by(Task.created_at.desc()).offset(offset).limit(per_page)
    )
    tasks = [TaskResponse.model_validate(t) for t in result.scalars().all()]
    return TaskListResponse(tasks=tasks, total=total)


# ---------------------------------------------------------------------------
# All transactions
# ---------------------------------------------------------------------------


@router.get("/transactions/", response_model=TransactionListResponse)
async def list_all_transactions(
    page: int = Query(1, ge=1),
    per_page: int = Query(20, ge=1, le=100),
    type: str | None = Query(None, description="Filter by transaction type"),
    admin: User = Depends(require_billing_or_super),
    db: AsyncSession = Depends(get_db),
) -> TransactionListResponse:
    """List all transactions across the platform (admin only)."""
    query = select(Transaction)
    if type:
        query = query.where(Transaction.type == type)

    total = (
        await db.execute(select(func.count()).select_from(query.subquery()))
    ).scalar_one()

    offset = (page - 1) * per_page
    result = await db.execute(
        query.order_by(Transaction.created_at.desc()).offset(offset).limit(per_page)
    )
    txns = [TransactionResponse.model_validate(t) for t in result.scalars().all()]
    return TransactionListResponse(transactions=txns, total=total)


# ---------------------------------------------------------------------------
# Agent admin control
# ---------------------------------------------------------------------------


class AgentStatusUpdate(BaseModel):
    status: AgentStatus


@router.put("/agents/{agent_id}/status", response_model=AgentResponse)
async def update_agent_status(
    agent_id: UUID,
    data: AgentStatusUpdate,
    request: Request,
    admin: User = Depends(require_ops_or_super),
    db: AsyncSession = Depends(get_db),
) -> AgentResponse:
    """Override agent status (suspend/activate) β€” admin only."""
    result = await db.execute(
        select(Agent).where(Agent.id == agent_id).options(selectinload(Agent.skills))
    )
    agent = result.scalar_one_or_none()
    if agent is None:
        raise HTTPException(status_code=404, detail="Agent not found")
    await audit_log(db, action="admin.update_agent_status", actor_user_id=str(admin.id), target_type="agent", target_id=agent_id, old_value={"status": agent.status}, new_value={"status": data.status.value}, request=request)
    agent.status = data.status.value
    await db.flush()
    await db.refresh(agent)
    return AgentResponse.model_validate(agent)


class AgentCapabilitiesUpdate(BaseModel):
    capabilities: dict


@router.put("/agents/{agent_id}/capabilities", response_model=AgentResponse)
async def update_agent_capabilities(
    agent_id: UUID,
    data: AgentCapabilitiesUpdate,
    request: Request,
    admin: User = Depends(require_ops_or_super),
    db: AsyncSession = Depends(get_db),
) -> AgentResponse:
    """Override agent capabilities (e.g. streaming) β€” admin only."""
    result = await db.execute(
        select(Agent).where(Agent.id == agent_id).options(selectinload(Agent.skills))
    )
    agent = result.scalar_one_or_none()
    if agent is None:
        raise HTTPException(status_code=404, detail="Agent not found")
    await audit_log(db, action="admin.update_agent_capabilities", actor_user_id=str(admin.id), target_type="agent", target_id=agent_id, old_value={"capabilities": agent.capabilities}, new_value={"capabilities": data.capabilities}, request=request)
    agent.capabilities = data.capabilities
    await db.commit()
    await db.refresh(agent)
    return AgentResponse.model_validate(agent)


class AgentPricingUpdate(BaseModel):
    pricing: dict


@router.put("/agents/{agent_id}/pricing", response_model=AgentResponse)
async def update_agent_pricing(
    agent_id: UUID,
    data: AgentPricingUpdate,
    request: Request,
    admin: User = Depends(require_ops_or_super),
    db: AsyncSession = Depends(get_db),
) -> AgentResponse:
    """Override agent pricing β€” admin only."""
    result = await db.execute(select(Agent).where(Agent.id == agent_id))
    agent = result.scalar_one_or_none()
    if agent is None:
        raise HTTPException(status_code=404, detail="Agent not found")
    await audit_log(db, action="admin.update_agent_pricing", actor_user_id=str(admin.id), target_type="agent", target_id=agent_id, old_value={"pricing": agent.pricing}, new_value={"pricing": data.pricing}, request=request)
    agent.pricing = data.pricing
    await db.commit()
    await db.refresh(agent)
    return AgentResponse.model_validate(agent)


class AgentVerificationUpdate(BaseModel):
    verification_level: VerificationLevel


@router.put("/agents/{agent_id}/verification", response_model=AgentResponse)
async def update_agent_verification(
    agent_id: UUID,
    data: AgentVerificationUpdate,
    request: Request,
    admin: User = Depends(require_ops_or_super),
    db: AsyncSession = Depends(get_db),
) -> AgentResponse:
    """Override agent verification level β€” admin only."""
    result = await db.execute(select(Agent).where(Agent.id == agent_id))
    agent = result.scalar_one_or_none()
    if agent is None:
        raise HTTPException(status_code=404, detail="Agent not found")
    await audit_log(db, action="admin.update_agent_verification", actor_user_id=str(admin.id), target_type="agent", target_id=agent_id, old_value={"verification_level": agent.verification_level}, new_value={"verification_level": data.verification_level.value}, request=request)
    agent.verification_level = data.verification_level.value
    await db.commit()
    await db.refresh(agent)
    return AgentResponse.model_validate(agent)


# ---------------------------------------------------------------------------
# Admin agent delete (bypasses ownership check)
# ---------------------------------------------------------------------------


@router.delete("/agents/{agent_id}", status_code=204)
async def admin_delete_agent(
    agent_id: UUID,
    request: Request,
    admin: User = Depends(require_ops_or_super),
    db: AsyncSession = Depends(get_db),
) -> None:
    """Permanently delete any agent β€” admin only, bypasses ownership check."""
    result = await db.execute(select(Agent).where(Agent.id == agent_id))
    agent = result.scalar_one_or_none()
    if agent is None:
        raise HTTPException(status_code=404, detail="Agent not found")
    await audit_log(
        db, action="admin.delete_agent", actor_user_id=str(admin.id),
        target_type="agent", target_id=agent_id,
        old_value={"name": agent.name, "owner_id": str(agent.owner_id)},
        new_value=None, request=request,
    )
    await db.delete(agent)
    await db.commit()


# ---------------------------------------------------------------------------
# Credit grants (admin only)
# ---------------------------------------------------------------------------


class AdminCreditGrant(BaseModel):
    user_id: UUID
    amount: float = Field(gt=0, le=100000)
    reason: str = Field(min_length=3, max_length=200)


@router.post("/credits/grant")
async def grant_credits(
    data: AdminCreditGrant,
    request: Request,
    admin: User = Depends(require_billing_or_super),
    db: AsyncSession = Depends(get_db),
):
    """Grant bonus credits to a user (admin only).

    Credits are added as BONUS type β€” spendable but never withdrawable
    via Stripe Connect payouts.
    """
    from src.services.credit_ledger import CreditLedgerService

    # Verify target user exists
    target = await db.get(User, data.user_id)
    if not target:
        raise HTTPException(status_code=404, detail="Target user not found")

    # SOC 2 separation of duties: admins cannot grant credits to themselves
    if target.id == admin.id:
        raise HTTPException(
            status_code=403,
            detail="Cannot grant credits to yourself. Ask another admin to grant credits to your account.",
        )

    ledger = CreditLedgerService(db)
    txn = await ledger.grant_bonus(
        owner_id=data.user_id,
        amount=data.amount,
        description=f"Admin grant: {data.reason}",
    )
    await audit_log(db, action="admin.grant_credits", actor_user_id=str(admin.id), target_type="user", target_id=data.user_id, new_value={"amount": data.amount, "reason": data.reason}, request=request)
    return {
        "transaction_id": str(txn.id),
        "amount": data.amount,
        "user_id": str(data.user_id),
        "reason": data.reason,
    }


# ---------------------------------------------------------------------------
# Re-embed all skills (admin only)
# ---------------------------------------------------------------------------


@router.post("/re-embed-skills")
async def re_embed_skills(
    request: Request,
    admin: User = Depends(require_ops_or_super),
    db: AsyncSession = Depends(get_db),
):
    """Re-generate embeddings for all skills using current embedding provider.

    Use this after switching from FakeProvider to a real provider (OpenAI, etc.)
    to replace hash-based vectors with semantically meaningful ones.
    """
    from src.core.embeddings import EmbeddingService
    from src.models.skill import AgentSkill

    embed_svc = EmbeddingService()  # uses platform key or provider config

    result = await db.execute(select(AgentSkill))
    skills = list(result.scalars().all())

    texts = [f"{s.name}: {s.description}" for s in skills]
    if not texts:
        return {"message": "No skills found", "updated": 0}

    embeddings = await embed_svc.generate_batch(texts)
    for skill, emb in zip(skills, embeddings):
        skill.embedding = emb

    await audit_log(db, action="admin.re_embed_skills", actor_user_id=str(admin.id), new_value={"skills_count": len(skills)}, request=request)
    await db.commit()
    return {"message": f"Re-embedded {len(skills)} skills", "updated": len(skills)}


# ------------------------------------------------------------------
# Health Monitor Admin Endpoints
# ------------------------------------------------------------------


@router.get("/health/overview")
async def health_overview(
    admin: User = Depends(require_ops_or_super),
    db: AsyncSession = Depends(get_db),
) -> dict:
    """Aggregate health stats β€” active, unavailable, failing agents."""
    from src.services.health_monitor import HealthMonitorService
    service = HealthMonitorService(db)
    return await service.get_health_overview()


@router.post("/agents/bulk-reactivate")
async def bulk_reactivate(
    request: Request,
    admin: User = Depends(require_ops_or_super),
    db: AsyncSession = Depends(get_db),
) -> dict:
    """Reactivate all UNAVAILABLE agents back to ACTIVE."""
    from src.services.health_monitor import HealthMonitorService
    service = HealthMonitorService(db)
    count = await service.bulk_reactivate_unavailable()
    await audit_log(
        db, action="admin.bulk_reactivate",
        actor_user_id=str(admin.id),
        target_type="agents",
        new_value={"reactivated": count},
        request=request,
    )
    return {"reactivated": count}


# ---------------------------------------------------------------------------
# Admin Channels
# ---------------------------------------------------------------------------


@router.get("/channels/")
async def admin_list_channels(
    platform: str | None = None,
    status: str | None = None,
    admin: User = Depends(require_ops_or_super),
    db: AsyncSession = Depends(get_db),
):
    """List all channels across all developers (admin only)."""
    from src.models.channel import ChannelConnection
    query = select(ChannelConnection).order_by(ChannelConnection.created_at.desc())
    if platform:
        query = query.where(ChannelConnection.platform == platform)
    if status:
        query = query.where(ChannelConnection.status == status)
    result = await db.execute(query)
    channels = result.scalars().all()

    # Get owner info for each channel
    owner_ids = {ch.owner_id for ch in channels}
    owners_result = await db.execute(select(User).where(User.id.in_(owner_ids)))
    owners = {u.id: u for u in owners_result.scalars().all()}

    return {"channels": [{
        **ChannelResponse.model_validate(ch).model_dump(),
        "owner_email": owners.get(ch.owner_id, User).email if ch.owner_id in owners else "",
        "owner_name": owners.get(ch.owner_id, User).name if ch.owner_id in owners else "",
    } for ch in channels], "total": len(channels)}


@router.get("/channels/{channel_id}")
async def admin_get_channel(
    channel_id: UUID,
    request: Request,
    admin: User = Depends(require_ops_or_super),
    db: AsyncSession = Depends(get_db),
):
    """Get channel detail with owner info (admin only)."""
    from src.models.channel import ChannelConnection
    result = await db.execute(select(ChannelConnection).where(ChannelConnection.id == channel_id))
    conn = result.scalar_one_or_none()
    if not conn:
        raise HTTPException(status_code=404, detail="Channel not found")

    owner = await db.get(User, conn.owner_id)
    await audit_log(db, action="admin.channel.view", actor_user_id=str(admin.id), target_type="channel", target_id=channel_id, request=request)

    response = ChannelResponse.model_validate(conn).model_dump()
    response["owner_email"] = owner.email if owner else ""
    response["owner_name"] = owner.name if owner else ""
    response["owner_credit_balance"] = float(owner.account.balance) if owner and owner.account else 0
    response["owner_account_tier"] = owner.account_tier if owner else "free"
    return response


@router.get("/channels/{channel_id}/messages")
async def admin_get_channel_messages(
    channel_id: UUID,
    justification: str = Query(..., description="Required: abuse_report, developer_support, legal_request, compliance_check"),
    direction: str | None = None,
    cursor: str | None = None,
    limit: int = Query(20, ge=1, le=100),
    request: Request = None,
    admin: User = Depends(require_ops_or_super),
    db: AsyncSession = Depends(get_db),
):
    """View channel messages β€” requires justification (SOC 2 CC7.2, GDPR Art. 28)."""
    valid_justifications = {"abuse_report", "developer_support", "legal_request", "compliance_check"}
    if justification not in valid_justifications:
        raise HTTPException(status_code=400, detail=f"justification must be one of: {', '.join(valid_justifications)}")

    # Audit log with justification
    await audit_log(db, action="admin.channel.view_messages", actor_user_id=str(admin.id), target_type="channel", target_id=channel_id, new_value={"justification": justification}, request=request)

    from src.services.channel_service import ChannelService
    from src.models.channel import ChannelConnection
    result = await db.execute(select(ChannelConnection).where(ChannelConnection.id == channel_id))
    conn = result.scalar_one_or_none()
    if not conn:
        raise HTTPException(status_code=404, detail="Channel not found")

    service = ChannelService(db)
    # Admin bypasses ownership β€” pass conn.owner_id directly
    return await service.get_channel_messages(channel_id, conn.owner_id, direction, cursor, limit)