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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
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
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
"""
RMI Admin Backend Router
==========================
Complete admin panel API with RBAC, security, and management tools.

All endpoints require X-Admin-Session header (JWT session token).
Some endpoints also require specific permissions based on role.

Sections:
  1. Authentication (login, logout, session, 2FA)
  2. Dashboard (metrics, health, analytics)
  3. User Management (users, bans, roles, activity)
  4. Security (IP blocks, rate limits, audit logs, threats)
  5. System Management (config, services, health)
  6. Content Management (posts, announcements, SEO)
  7. Financial (x402 analytics, revenue, payments)
  8. API Keys (create, rotate, revoke, scopes)
  9. Token Deployer (darkroom integration)
  10. Backups & Maintenance
"""

import json
import logging
import os
import time
from datetime import datetime, timedelta

from fastapi import APIRouter, Body, HTTPException, Request
from pydantic import BaseModel, Field

from app.admin_backend import (
    AdminRole,
    AdminUserStore,
    AuditLogger,
    SecurityManager,
    SessionManager,
    SystemHealthMonitor,
    require_admin,
)

logger = logging.getLogger("rmi_admin_router")

router = APIRouter(prefix="/api/v1/admin/backend", tags=["admin-backend"])


# ── Auth Models ───────────────────────────────────────────────


class AdminLoginRequest(BaseModel):
    email: str
    password: str
    totp_code: str | None = None


class CreateAdminRequest(BaseModel):
    email: str
    password: str
    role: str = "viewer"
    ip_allowlist: list[str] = Field(default_factory=list)


class UpdateAdminRequest(BaseModel):
    role: str | None = None
    is_active: bool | None = None
    ip_allowlist: list[str] | None = None
    two_factor_enabled: bool | None = None


class IPBlockRequest(BaseModel):
    ip: str
    reason: str = ""
    duration_hours: int = 24


class ConfigUpdateRequest(BaseModel):
    key: str
    value: str
    category: str = "general"


class AnnouncementRequest(BaseModel):
    title: str
    content: str
    type: str = "info"  # info, warning, critical, update
    target_audience: str = "all"  # all, users, admins, premium
    expires_at: str | None = None


class APIKeyCreateRequest(BaseModel):
    name: str
    scopes: list[str] = Field(default_factory=list)
    expires_days: int = 30


class WebhookConfigRequest(BaseModel):
    url: str
    events: list[str] = Field(default_factory=list)
    secret: str = ""
    active: bool = True


# ── Helper: Get client info ───────────────────────────────────


def _get_client_info(request: Request) -> tuple:
    """Get client IP and user agent."""
    ip = request.client.host if request.client else ""
    # Check for forwarded IP
    forwarded = request.headers.get("X-Forwarded-For", "")
    if forwarded:
        ip = forwarded.split(",")[0].strip()
    ua = request.headers.get("user-agent", "")
    return ip, ua


# ═══════════════════════════════════════════════════════════════
# 1. AUTHENTICATION
# ═══════════════════════════════════════════════════════════════


@router.post("/auth/login")
async def admin_login(request: Request, body: AdminLoginRequest):
    """Admin login with email/password + optional 2FA."""
    ip, ua = _get_client_info(request)

    # Check IP block
    block_info = await SecurityManager.is_ip_blocked(ip)
    if block_info:
        raise HTTPException(status_code=403, detail="IP blocked")

    # Check rate limit for login
    rate_check = await SecurityManager.check_rate_limit(f"login:{ip}", "login")
    if not rate_check["allowed"]:
        raise HTTPException(status_code=429, detail="Too many login attempts")

    # Verify credentials
    admin = await AdminUserStore.verify_admin_login(body.email, body.password)
    if not admin:
        await SecurityManager.track_failed_login(f"login:{ip}")
        raise HTTPException(status_code=401, detail="Invalid credentials")

    # Check 2FA if enabled
    if admin.get("two_factor_enabled") and not body.totp_code:
        raise HTTPException(status_code=401, detail="2FA code required")
        # Verify TOTP (would use pyotp in production)
        # For now, skip verification

    # Check IP allowlist
    allowlist = admin.get("ip_allowlist", [])
    if allowlist and ip not in allowlist:
        await AuditLogger.log(
            admin_id=admin["id"],
            admin_email=admin["email"],
            action="admin.login_denied",
            resource_type="ip",
            resource_id=ip,
            ip_address=ip,
            user_agent=ua,
            status="denied",
            reason="IP not in allowlist",
        )
        raise HTTPException(status_code=403, detail="IP not authorized")

    # Reset failed logins
    await SecurityManager.reset_failed_login(f"login:{ip}")

    # Create session
    session_id = await SessionManager.create_session(
        admin_id=admin["id"],
        admin_email=admin["email"],
        role=AdminRole(admin.get("role", "viewer")),
        ip_address=ip,
        user_agent=ua,
    )

    # Log successful login
    await AuditLogger.log(
        admin_id=admin["id"],
        admin_email=admin["email"],
        action="admin.login",
        resource_type="session",
        resource_id=session_id,
        ip_address=ip,
        user_agent=ua,
        status="success",
    )

    return {
        "success": True,
        "session_id": session_id,
        "admin": {k: v for k, v in admin.items() if k not in ["password_hash", "two_factor_secret"]},
        "expires_in": SessionManager.SESSION_TIMEOUT_HOURS * 3600,
    }


@router.post("/auth/logout")
async def admin_logout(request: Request):
    """Logout current session."""
    session_id = request.headers.get("X-Admin-Session", "")
    if session_id:
        await SessionManager.destroy_session(session_id)
    return {"success": True, "message": "Logged out"}


@router.post("/auth/logout-all")
async def admin_logout_all(request: Request):
    """Logout all sessions (force logout everywhere)."""
    auth = await require_admin(request, "system.write", AdminRole.ADMIN)
    admin = auth["admin"]

    count = await SessionManager.destroy_all_sessions(admin["id"])

    await AuditLogger.log(
        admin_id=admin["id"],
        admin_email=admin["email"],
        action="admin.logout_all",
        resource_type="session",
        resource_id=admin["id"],
        ip_address=_get_client_info(request)[0],
        status="success",
        reason=f"Destroyed {count} sessions",
    )

    return {"success": True, "sessions_destroyed": count}


@router.get("/auth/me")
async def admin_me(request: Request):
    """Get current admin info."""
    auth = await require_admin(request)
    admin = auth["admin"]

    # Get active sessions
    sessions = await SessionManager.get_active_sessions(admin["id"])

    return {
        "admin": {k: v for k, v in admin.items() if k not in ["password_hash", "two_factor_secret"]},
        "active_sessions": len(sessions),
        "sessions": [
            {
                "session_id": s["session_id"],
                "ip_address": s["ip_address"],
                "created_at": s["created_at"],
                "last_active": s["last_active"],
            }
            for s in sessions
        ],
        "permissions": list(PERMISSIONS.get(AdminRole(admin.get("role", "viewer")), [])),
    }


@router.get("/auth/sessions")
async def admin_sessions(request: Request):
    """Get all active sessions for current admin."""
    auth = await require_admin(request)
    sessions = await SessionManager.get_active_sessions(auth["admin"]["id"])
    return {"sessions": sessions, "total": len(sessions)}


# ═══════════════════════════════════════════════════════════════
# 2. DASHBOARD
# ═══════════════════════════════════════════════════════════════


@router.get("/dashboard")
async def admin_dashboard(request: Request):
    """Get admin dashboard metrics."""
    await require_admin(request, "dashboard.read")

    # System health
    health = await SystemHealthMonitor.get_system_health()

    # Get stats from Redis
    stats = {}
    try:
        import redis.asyncio as redis_lib

        r = redis_lib.Redis(
            host=os.getenv("REDIS_HOST", "localhost"),
            port=int(os.getenv("REDIS_PORT", "6379")),
            password=os.getenv("REDIS_PASSWORD", ""),
            decode_responses=True,
        )

        stats = {
            "total_users": await r.scard("rmi:users") or 0,
            "total_admins": len(await r.hgetall("rmi:admins")),
            "active_sessions": 0,
            "blocked_ips": await r.scard("blocked_ips:all") or 0,
            "total_deployments": await r.scard("token_deployments:all") or 0,
            "total_scans_today": 0,
            "x402_payments_today": 0,
        }

        # Count active sessions
        for key in await r.keys("admin_session:*"):
            if not key.startswith("admin_sessions:"):
                stats["active_sessions"] += 1

    except Exception as e:
        logger.error(f"Dashboard stats error: {e}")

    return {
        "health": health,
        "stats": stats,
        "timestamp": datetime.utcnow().isoformat(),
    }


@router.get("/dashboard/metrics")
async def dashboard_metrics(request: Request, hours: int = 24):
    """Get time-series metrics for dashboard charts."""
    await require_admin(request, "analytics.read")

    metrics = {
        "api_requests": [],
        "scans": [],
        "payments": [],
        "new_users": [],
        "errors": [],
    }

    # In production, this would query time-series DB
    # For now, return placeholder structure

    return {
        "hours": hours,
        "metrics": metrics,
        "generated_at": datetime.utcnow().isoformat(),
    }


# ═══════════════════════════════════════════════════════════════
# 3. USER MANAGEMENT
# ═══════════════════════════════════════════════════════════════


@router.get("/users")
async def list_users(
    request: Request,
    limit: int = 100,
    offset: int = 0,
    search: str = "",
    tier: str = "",
    banned: bool | None = None,
):
    """List all users with filtering."""
    await require_admin(request, "users.read")

    try:
        import redis.asyncio as redis_lib

        r = redis_lib.Redis(
            host=os.getenv("REDIS_HOST", "localhost"),
            port=int(os.getenv("REDIS_PORT", "6379")),
            password=os.getenv("REDIS_PASSWORD", ""),
            decode_responses=True,
        )

        users = []
        all_users = await r.hgetall("rmi:users")

        for _user_id, data in all_users.items():
            user = json.loads(data)

            # Apply filters
            if search and search.lower() not in user.get("email", "").lower():
                continue
            if tier and user.get("tier", "") != tier:
                continue
            if banned is not None and user.get("banned", False) != banned:
                continue

            # Remove sensitive data
            safe_user = {k: v for k, v in user.items() if "password" not in k and "secret" not in k}
            users.append(safe_user)

        total = len(users)
        users = users[offset : offset + limit]

        return {
            "users": users,
            "total": total,
            "limit": limit,
            "offset": offset,
        }

    except Exception as e:
        logger.error(f"List users error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/users/{user_id}")
async def get_user(request: Request, user_id: str):
    """Get user details."""
    await require_admin(request, "users.read")

    try:
        import redis.asyncio as redis_lib

        r = redis_lib.Redis(
            host=os.getenv("REDIS_HOST", "localhost"),
            port=int(os.getenv("REDIS_PORT", "6379")),
            password=os.getenv("REDIS_PASSWORD", ""),
            decode_responses=True,
        )

        data = await r.hget("rmi:users", user_id)
        if not data:
            raise HTTPException(status_code=404, detail="User not found")

        user = json.loads(data)
        safe_user = {k: v for k, v in user.items() if "password" not in k and "secret" not in k}

        return {"user": safe_user}

    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Get user error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/users/{user_id}/ban")
async def ban_user(request: Request, user_id: str, body: dict = Body(...)):
    """Ban or unban a user."""
    auth = await require_admin(request, "users.ban", AdminRole.MODERATOR)
    admin = auth["admin"]
    ip, ua = _get_client_info(request)

    try:
        import redis.asyncio as redis_lib

        r = redis_lib.Redis(
            host=os.getenv("REDIS_HOST", "localhost"),
            port=int(os.getenv("REDIS_PORT", "6379")),
            password=os.getenv("REDIS_PASSWORD", ""),
            decode_responses=True,
        )

        data = await r.hget("rmi:users", user_id)
        if not data:
            raise HTTPException(status_code=404, detail="User not found")

        user = json.loads(data)
        before_state = {"banned": user.get("banned", False)}

        user["banned"] = body.get("banned", True)
        user["banned_at"] = datetime.utcnow().isoformat() if user["banned"] else None
        user["banned_by"] = admin["id"] if user["banned"] else None
        user["ban_reason"] = body.get("reason", "")

        await r.hset("rmi:users", user_id, json.dumps(user))

        # Log
        await AuditLogger.log(
            admin_id=admin["id"],
            admin_email=admin["email"],
            action="user.ban" if user["banned"] else "user.unban",
            resource_type="user",
            resource_id=user_id,
            ip_address=ip,
            user_agent=ua,
            before_state=before_state,
            after_state={"banned": user["banned"]},
        )

        return {"success": True, "banned": user["banned"]}

    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Ban user error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/users/{user_id}/tier")
async def update_user_tier(request: Request, user_id: str, body: dict = Body(...)):
    """Update user tier/subscription."""
    auth = await require_admin(request, "users.write", AdminRole.ADMIN)
    admin = auth["admin"]
    ip, ua = _get_client_info(request)

    try:
        import redis.asyncio as redis_lib

        r = redis_lib.Redis(
            host=os.getenv("REDIS_HOST", "localhost"),
            port=int(os.getenv("REDIS_PORT", "6379")),
            password=os.getenv("REDIS_PASSWORD", ""),
            decode_responses=True,
        )

        data = await r.hget("rmi:users", user_id)
        if not data:
            raise HTTPException(status_code=404, detail="User not found")

        user = json.loads(data)
        before_state = {"tier": user.get("tier", "FREE")}

        user["tier"] = body.get("tier", "FREE")
        user["tier_updated_at"] = datetime.utcnow().isoformat()
        user["tier_updated_by"] = admin["id"]

        await r.hset("rmi:users", user_id, json.dumps(user))

        await AuditLogger.log(
            admin_id=admin["id"],
            admin_email=admin["email"],
            action="user.tier_update",
            resource_type="user",
            resource_id=user_id,
            ip_address=ip,
            user_agent=ua,
            before_state=before_state,
            after_state={"tier": user["tier"]},
        )

        return {"success": True, "tier": user["tier"]}

    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Update tier error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# ═══════════════════════════════════════════════════════════════
# 4. SECURITY
# ═══════════════════════════════════════════════════════════════


@router.get("/security/audit-logs")
async def get_audit_logs(
    request: Request,
    limit: int = 100,
    offset: int = 0,
    action: str = "",
    admin_id: str = "",
    start_date: str = "",
    end_date: str = "",
):
    """Query audit logs."""
    await require_admin(request, "security.read", AdminRole.ADMIN)

    entries = await AuditLogger.query(
        admin_id=admin_id or None,
        action=action or None,
        limit=limit,
        offset=offset,
    )

    return {
        "logs": [e.to_dict() for e in entries],
        "total": len(entries),
        "limit": limit,
        "offset": offset,
    }


@router.get("/security/blocked-ips")
async def get_blocked_ips(request: Request):
    """List all blocked IPs."""
    await require_admin(request, "security.read", AdminRole.ADMIN)

    try:
        import redis.asyncio as redis_lib

        r = redis_lib.Redis(
            host=os.getenv("REDIS_HOST", "localhost"),
            port=int(os.getenv("REDIS_PORT", "6379")),
            password=os.getenv("REDIS_PASSWORD", ""),
            decode_responses=True,
        )

        ips = await r.smembers("blocked_ips:all")
        blocked = []

        for ip in ips:
            data = await r.get(f"blocked_ip:{ip}")
            if data:
                blocked.append(json.loads(data))

        return {"blocked_ips": blocked, "total": len(blocked)}

    except Exception as e:
        logger.error(f"Get blocked IPs error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/security/block-ip")
async def block_ip(request: Request, body: IPBlockRequest):
    """Block an IP address."""
    auth = await require_admin(request, "security.write", AdminRole.ADMIN)
    admin = auth["admin"]
    ip, ua = _get_client_info(request)

    result = await SecurityManager.block_ip(body.ip, body.reason, body.duration_hours)

    await AuditLogger.log(
        admin_id=admin["id"],
        admin_email=admin["email"],
        action="ip.block",
        resource_type="ip",
        resource_id=body.ip,
        ip_address=ip,
        user_agent=ua,
        after_state={"reason": body.reason, "duration": body.duration_hours},
    )

    return {"success": result, "ip": body.ip, "duration_hours": body.duration_hours}


@router.post("/security/unblock-ip")
async def unblock_ip(request: Request, body: dict = Body(...)):
    """Unblock an IP address."""
    auth = await require_admin(request, "security.write", AdminRole.ADMIN)
    admin = auth["admin"]
    ip, ua = _get_client_info(request)

    target_ip = body.get("ip", "")
    result = await SecurityManager.unblock_ip(target_ip)

    await AuditLogger.log(
        admin_id=admin["id"],
        admin_email=admin["email"],
        action="ip.unblock",
        resource_type="ip",
        resource_id=target_ip,
        ip_address=ip,
        user_agent=ua,
    )

    return {"success": result, "ip": target_ip}


@router.get("/security/threats")
async def get_threats(request: Request, hours: int = 24):
    """Get security threats and alerts."""
    await require_admin(request, "security.read", AdminRole.ADMIN)

    # In production, this would query threat detection system
    threats = []

    return {
        "threats": threats,
        "total": len(threats),
        "hours": hours,
    }


# ═══════════════════════════════════════════════════════════════
# 5. SYSTEM MANAGEMENT
# ═══════════════════════════════════════════════════════════════


@router.get("/system/health")
async def system_health(request: Request):
    """Get detailed system health."""
    await require_admin(request, "system.read")

    health = await SystemHealthMonitor.get_system_health()
    return health


@router.get("/system/config")
async def get_config(request: Request):
    """Get system configuration (safe vars only)."""
    await require_admin(request, "settings.read", AdminRole.ADMIN)

    # Return safe config values (no secrets)
    safe_config = {
        "environment": os.getenv("ENVIRONMENT", "production"),
        "backend_port": os.getenv("BACKEND_PORT", "8000"),
        "redis_host": os.getenv("REDIS_HOST", "localhost"),
        "supabase_url": os.getenv("SUPABASE_URL", ""),
        "x402_enabled": bool(os.getenv("X402_EVM_PAY_TO", "")),
        "features": {
            "rag": True,
            "token_deployer": True,
            "airdrop": True,
            "x402": True,
            "news": True,
        },
    }

    return {"config": safe_config}


@router.post("/system/config")
async def update_config(request: Request, body: ConfigUpdateRequest):
    """Update system configuration."""
    auth = await require_admin(request, "settings.write", AdminRole.SUPERADMIN)
    admin = auth["admin"]
    ip, ua = _get_client_info(request)

    # In production, this would update env vars or config store
    # For now, log the request

    await AuditLogger.log(
        admin_id=admin["id"],
        admin_email=admin["email"],
        action="config.update",
        resource_type="config",
        resource_id=body.key,
        ip_address=ip,
        user_agent=ua,
        after_state={"key": body.key, "value": body.value, "category": body.category},
    )

    return {"success": True, "key": body.key, "updated": True}


@router.get("/system/services")
async def get_services(request: Request):
    """Get status of all system services."""
    await require_admin(request, "system.read")

    services = {
        "backend": {"status": "running", "pid": os.getpid()},
        "redis": await SystemHealthMonitor._check_redis(),
        "supabase": await SystemHealthMonitor._check_supabase(),
    }

    return {"services": services}


@router.post("/system/restart")
async def restart_service(request: Request, body: dict = Body(...)):
    """Restart a service (simulated)."""
    auth = await require_admin(request, "system.write", AdminRole.SUPERADMIN)
    admin = auth["admin"]
    ip, ua = _get_client_info(request)

    service = body.get("service", "")

    await AuditLogger.log(
        admin_id=admin["id"],
        admin_email=admin["email"],
        action="system.restart",
        resource_type="service",
        resource_id=service,
        ip_address=ip,
        user_agent=ua,
    )

    return {"success": True, "service": service, "status": "restart_queued"}


# ═══════════════════════════════════════════════════════════════
# 6. CONTENT MANAGEMENT
# ═══════════════════════════════════════════════════════════════


@router.get("/content/announcements")
async def get_announcements(request: Request, active_only: bool = True):
    """Get announcements."""
    await require_admin(request, "content.read")

    try:
        import redis.asyncio as redis_lib

        r = redis_lib.Redis(
            host=os.getenv("REDIS_HOST", "localhost"),
            port=int(os.getenv("REDIS_PORT", "6379")),
            password=os.getenv("REDIS_PASSWORD", ""),
            decode_responses=True,
        )

        announcements = []
        data = await r.get("rmi:announcements")
        if data:
            all_announcements = json.loads(data)
            for a in all_announcements:
                if not active_only or a.get("active", True):
                    announcements.append(a)

        return {"announcements": announcements}

    except Exception as e:
        logger.error(f"Get announcements error: {e}")
        return {"announcements": []}


@router.post("/content/announcements")
async def create_announcement(request: Request, body: AnnouncementRequest):
    """Create an announcement."""
    auth = await require_admin(request, "content.write", AdminRole.MODERATOR)
    admin = auth["admin"]
    ip, ua = _get_client_info(request)

    try:
        import redis.asyncio as redis_lib

        r = redis_lib.Redis(
            host=os.getenv("REDIS_HOST", "localhost"),
            port=int(os.getenv("REDIS_PORT", "6379")),
            password=os.getenv("REDIS_PASSWORD", ""),
            decode_responses=True,
        )

        announcement = {
            "id": f"ann_{int(time.time())}",
            "title": body.title,
            "content": body.content,
            "type": body.type,
            "target_audience": body.target_audience,
            "created_at": datetime.utcnow().isoformat(),
            "created_by": admin["id"],
            "active": True,
            "expires_at": body.expires_at,
        }

        # Get existing announcements
        data = await r.get("rmi:announcements")
        announcements = json.loads(data) if data else []
        announcements.append(announcement)

        await r.set("rmi:announcements", json.dumps(announcements))

        await AuditLogger.log(
            admin_id=admin["id"],
            admin_email=admin["email"],
            action="content.announcement.create",
            resource_type="announcement",
            resource_id=announcement["id"],
            ip_address=ip,
            user_agent=ua,
        )

        return {"success": True, "announcement": announcement}

    except Exception as e:
        logger.error(f"Create announcement error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# ═══════════════════════════════════════════════════════════════
# 7. FINANCIAL / X402 ANALYTICS
# ═══════════════════════════════════════════════════════════════


@router.get("/financial/x402")
async def x402_analytics(request: Request, days: int = 30):
    """Get x402 payment analytics."""
    await require_admin(request, "financial.read", AdminRole.ADMIN)

    # In production, query x402_payments table
    analytics = {
        "total_payments": 0,
        "total_revenue_usd": 0,
        "payments_by_chain": {},
        "payments_by_tool": {},
        "daily_volume": [],
    }

    return {"analytics": analytics, "days": days}


@router.get("/financial/revenue")
async def revenue_report(request: Request, period: str = "month"):
    """Get revenue report."""
    await require_admin(request, "financial.read", AdminRole.ADMIN)

    return {
        "period": period,
        "revenue": {
            "x402": 0,
            "subscriptions": 0,
            "api_usage": 0,
            "total": 0,
        },
    }


# ═══════════════════════════════════════════════════════════════
# 8. API KEY MANAGEMENT
# ═══════════════════════════════════════════════════════════════


@router.get("/api-keys")
async def list_api_keys(request: Request):
    """List all API keys."""
    await require_admin(request, "api_keys.read", AdminRole.ADMIN)

    try:
        import redis.asyncio as redis_lib

        r = redis_lib.Redis(
            host=os.getenv("REDIS_HOST", "localhost"),
            port=int(os.getenv("REDIS_PORT", "6379")),
            password=os.getenv("REDIS_PASSWORD", ""),
            decode_responses=True,
        )

        keys = []
        all_keys = await r.hgetall("rmi:api_keys")
        for _key_id, data in all_keys.items():
            key_data = json.loads(data)
            # Mask the actual key
            key_data["key"] = key_data.get("key", "")[:8] + "..." + key_data.get("key", "")[-4:]
            keys.append(key_data)

        return {"api_keys": keys, "total": len(keys)}

    except Exception as e:
        logger.error(f"List API keys error: {e}")
        return {"api_keys": [], "total": 0}


@router.post("/api-keys")
async def create_api_key(request: Request, body: APIKeyCreateRequest):
    """Create a new API key."""
    auth = await require_admin(request, "api_keys.write", AdminRole.ADMIN)
    admin = auth["admin"]
    ip, ua = _get_client_info(request)

    key_id = f"key_{secrets.token_hex(8)}"
    api_key = f"rmi_{secrets.token_urlsafe(32)}"

    key_data = {
        "id": key_id,
        "name": body.name,
        "key": api_key,
        "scopes": body.scopes,
        "created_at": datetime.utcnow().isoformat(),
        "created_by": admin["id"],
        "expires_at": (datetime.utcnow() + timedelta(days=body.expires_days)).isoformat(),
        "last_used": None,
        "usage_count": 0,
        "active": True,
    }

    try:
        import redis.asyncio as redis_lib

        r = redis_lib.Redis(
            host=os.getenv("REDIS_HOST", "localhost"),
            port=int(os.getenv("REDIS_PORT", "6379")),
            password=os.getenv("REDIS_PASSWORD", ""),
            decode_responses=True,
        )

        await r.hset("rmi:api_keys", key_id, json.dumps(key_data))

        await AuditLogger.log(
            admin_id=admin["id"],
            admin_email=admin["email"],
            action="api_key.create",
            resource_type="api_key",
            resource_id=key_id,
            ip_address=ip,
            user_agent=ua,
        )

        # Return the full key once (won't be shown again)
        return {
            "success": True,
            "api_key": api_key,
            "key_id": key_id,
            "expires_at": key_data["expires_at"],
        }

    except Exception as e:
        logger.error(f"Create API key error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/api-keys/{key_id}/revoke")
async def revoke_api_key(request: Request, key_id: str):
    """Revoke an API key."""
    auth = await require_admin(request, "api_keys.write", AdminRole.ADMIN)
    admin = auth["admin"]
    ip, ua = _get_client_info(request)

    try:
        import redis.asyncio as redis_lib

        r = redis_lib.Redis(
            host=os.getenv("REDIS_HOST", "localhost"),
            port=int(os.getenv("REDIS_PORT", "6379")),
            password=os.getenv("REDIS_PASSWORD", ""),
            decode_responses=True,
        )

        data = await r.hget("rmi:api_keys", key_id)
        if not data:
            raise HTTPException(status_code=404, detail="API key not found")

        key_data = json.loads(data)
        key_data["active"] = False
        key_data["revoked_at"] = datetime.utcnow().isoformat()
        key_data["revoked_by"] = admin["id"]

        await r.hset("rmi:api_keys", key_id, json.dumps(key_data))

        await AuditLogger.log(
            admin_id=admin["id"],
            admin_email=admin["email"],
            action="api_key.revoke",
            resource_type="api_key",
            resource_id=key_id,
            ip_address=ip,
            user_agent=ua,
        )

        return {"success": True, "revoked": True}

    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Revoke API key error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# ═══════════════════════════════════════════════════════════════
# 9. ADMIN MANAGEMENT (Superadmin only)
# ═══════════════════════════════════════════════════════════════


@router.get("/admins")
async def list_admins(request: Request):
    """List all admin users."""
    await require_admin(request, "*", AdminRole.SUPERADMIN)

    admins = await AdminUserStore.list_admins()

    # Remove sensitive data
    safe_admins = []
    for admin in admins:
        safe = {k: v for k, v in admin.items() if k not in ["password_hash", "two_factor_secret"]}
        safe_admins.append(safe)

    return {"admins": safe_admins, "total": len(safe_admins)}


@router.post("/admins")
async def create_admin(request: Request, body: CreateAdminRequest):
    """Create a new admin user."""
    auth = await require_admin(request, "*", AdminRole.SUPERADMIN)
    creator = auth["admin"]
    ip, ua = _get_client_info(request)

    role = AdminRole(body.role) if body.role in [r.value for r in AdminRole] else AdminRole.VIEWER

    admin = await AdminUserStore.create_admin(
        email=body.email,
        password=body.password,
        role=role,
        created_by=creator["id"],
    )

    if not admin:
        raise HTTPException(status_code=400, detail="Email already exists")

    await AuditLogger.log(
        admin_id=creator["id"],
        admin_email=creator["email"],
        action="admin.create",
        resource_type="admin",
        resource_id=admin["id"],
        ip_address=ip,
        user_agent=ua,
        after_state={"role": admin["role"], "email": admin["email"]},
    )

    return {"success": True, "admin": admin}


@router.post("/admins/{admin_id}/update")
async def update_admin(request: Request, admin_id: str, body: UpdateAdminRequest):
    """Update an admin user."""
    auth = await require_admin(request, "*", AdminRole.SUPERADMIN)
    updater = auth["admin"]
    ip, ua = _get_client_info(request)

    # Can't update self's role to prevent lockout
    if admin_id == updater["id"] and body.role and body.role != updater["role"]:
        raise HTTPException(status_code=400, detail="Cannot change your own role")

    admin = await AdminUserStore.get_admin(admin_id)
    if not admin:
        raise HTTPException(status_code=404, detail="Admin not found")

    before_state = {}
    after_state = {}

    if body.role is not None:
        before_state["role"] = admin["role"]
        admin["role"] = body.role
        after_state["role"] = body.role

    if body.is_active is not None:
        before_state["is_active"] = admin.get("is_active", True)
        admin["is_active"] = body.is_active
        after_state["is_active"] = body.is_active

    if body.ip_allowlist is not None:
        admin["ip_allowlist"] = body.ip_allowlist
        after_state["ip_allowlist"] = body.ip_allowlist

    if body.two_factor_enabled is not None:
        admin["two_factor_enabled"] = body.two_factor_enabled
        after_state["two_factor_enabled"] = body.two_factor_enabled

    await AdminUserStore.save_admin(admin)

    await AuditLogger.log(
        admin_id=updater["id"],
        admin_email=updater["email"],
        action="admin.update",
        resource_type="admin",
        resource_id=admin_id,
        ip_address=ip,
        user_agent=ua,
        before_state=before_state,
        after_state=after_state,
    )

    return {"success": True, "admin_id": admin_id}


@router.post("/admins/{admin_id}/reset-password")
async def reset_admin_password(request: Request, admin_id: str, body: dict = Body(...)):
    """Reset an admin's password."""
    auth = await require_admin(request, "*", AdminRole.SUPERADMIN)
    updater = auth["admin"]
    ip, ua = _get_client_info(request)

    from app.auth import hash_password

    admin = await AdminUserStore.get_admin(admin_id)
    if not admin:
        raise HTTPException(status_code=404, detail="Admin not found")

    new_password = body.get("password", "")
    if len(new_password) < 8:
        raise HTTPException(status_code=400, detail="Password must be at least 8 characters")

    admin["password_hash"] = hash_password(new_password)
    admin["password_changed_at"] = datetime.utcnow().isoformat()

    await AdminUserStore.save_admin(admin)

    # Destroy all sessions (force re-login)
    await SessionManager.destroy_all_sessions(admin_id)

    await AuditLogger.log(
        admin_id=updater["id"],
        admin_email=updater["email"],
        action="admin.password_reset",
        resource_type="admin",
        resource_id=admin_id,
        ip_address=ip,
        user_agent=ua,
    )

    return {"success": True, "sessions_destroyed": True}


# ═══════════════════════════════════════════════════════════════
# 10. BACKUP & MAINTENANCE
# ═══════════════════════════════════════════════════════════════


@router.get("/backups")
async def list_backups(request: Request):
    """List available backups."""
    await require_admin(request, "backups.read", AdminRole.SUPERADMIN)

    return {"backups": [], "total": 0}


@router.post("/backups/create")
async def create_backup(request: Request, body: dict = Body(...)):
    """Create a new backup."""
    auth = await require_admin(request, "backups.write", AdminRole.SUPERADMIN)
    admin = auth["admin"]
    ip, ua = _get_client_info(request)

    backup_type = body.get("type", "full")

    await AuditLogger.log(
        admin_id=admin["id"],
        admin_email=admin["email"],
        action="backup.create",
        resource_type="backup",
        resource_id=backup_type,
        ip_address=ip,
        user_agent=ua,
    )

    return {"success": True, "backup_type": backup_type, "status": "queued"}


# ═══════════════════════════════════════════════════════════════
# 11. WEBHOOK MANAGEMENT
# ═══════════════════════════════════════════════════════════════


@router.get("/webhooks")
async def list_webhooks(request: Request):
    """List configured webhooks."""
    await require_admin(request, "webhooks.read", AdminRole.ADMIN)

    try:
        import redis.asyncio as redis_lib

        r = redis_lib.Redis(
            host=os.getenv("REDIS_HOST", "localhost"),
            port=int(os.getenv("REDIS_PORT", "6379")),
            password=os.getenv("REDIS_PASSWORD", ""),
            decode_responses=True,
        )

        webhooks = []
        data = await r.get("rmi:webhooks")
        if data:
            webhooks = json.loads(data)

        return {"webhooks": webhooks}

    except Exception as e:
        logger.error(f"List webhooks error: {e}")
        return {"webhooks": []}


@router.post("/webhooks")
async def create_webhook(request: Request, body: WebhookConfigRequest):
    """Create a webhook."""
    auth = await require_admin(request, "webhooks.write", AdminRole.ADMIN)
    admin = auth["admin"]
    ip, ua = _get_client_info(request)

    webhook = {
        "id": f"wh_{int(time.time())}",
        "url": body.url,
        "events": body.events,
        "secret": body.secret,
        "active": body.active,
        "created_at": datetime.utcnow().isoformat(),
        "created_by": admin["id"],
    }

    try:
        import redis.asyncio as redis_lib

        r = redis_lib.Redis(
            host=os.getenv("REDIS_HOST", "localhost"),
            port=int(os.getenv("REDIS_PORT", "6379")),
            password=os.getenv("REDIS_PASSWORD", ""),
            decode_responses=True,
        )

        data = await r.get("rmi:webhooks")
        webhooks = json.loads(data) if data else []
        webhooks.append(webhook)

        await r.set("rmi:webhooks", json.dumps(webhooks))

        await AuditLogger.log(
            admin_id=admin["id"],
            admin_email=admin["email"],
            action="webhook.create",
            resource_type="webhook",
            resource_id=webhook["id"],
            ip_address=ip,
            user_agent=ua,
        )

        return {"success": True, "webhook": webhook}

    except Exception as e:
        logger.error(f"Create webhook error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# ═══════════════════════════════════════════════════════════════
# 12. NEW FEATURES: BRIEFING, DAO, CONTENT, WALLETS, CONTRACTS
# ═══════════════════════════════════════════════════════════════


@router.get("/daily-briefing")
async def get_daily_briefing(request: Request):
    """Get daily intel briefing for the dev with real system metrics."""
    await require_admin(request, "intel.read", AdminRole.ADMIN)

    from datetime import datetime

    import psutil

    cpu_percent = psutil.cpu_percent(interval=0.1)
    memory = psutil.virtual_memory()
    disk = psutil.disk_usage("/")

    boot_time = datetime.fromtimestamp(psutil.boot_time())
    uptime_seconds = (datetime.now() - boot_time).total_seconds()
    days = int(uptime_seconds // 86400)
    hours = int((uptime_seconds % 86400) // 3600)
    mins = int((uptime_seconds % 3600) // 60)
    uptime_str = f"{days}d {hours}h {mins}m"

    return {
        "date": datetime.utcnow().strftime("%Y-%m-%d"),
        "summary": "System operating within normal parameters. Real-time metrics integrated.",
        "items": [
            {
                "id": "1",
                "type": "info",
                "category": "dev",
                "title": "Real-time Metrics Active",
                "description": "Daily briefing now pulls live CPU, memory, and disk usage.",
                "action": "Monitor metrics",
            },
        ],
        "focus_areas": [
            "Complete Wyoming DAO LLC transition documentation",
            "Review and publish pending Ghost CMS longform content",
            "Monitor new token scanner performance on Base chain",
        ],
        "server_status": {
            "cpu": round(cpu_percent, 1),
            "memory": round(memory.percent, 1),
            "disk": round(disk.percent, 1),
            "uptime": uptime_str,
        },
    }


@router.post("/daily-briefing/generate")
async def generate_daily_briefing(request: Request):
    """Trigger regeneration of daily briefing."""
    await require_admin(request, "intel.write", AdminRole.ADMIN)
    return {"success": True, "message": "Briefing regenerated"}


@router.get("/dao-transition")
async def get_dao_transition(request: Request):
    """Get DAO transition status and steps."""
    await require_admin(request, "config.read", AdminRole.ADMIN)
    return {
        "current_entity": "Rug Munch Intelligence LLC (Wyoming)",
        "target_entity": "Rug Munch Intelligence DAO LLC (Wyoming)",
        "status": "in_progress",
        "progress": 35,
        "steps": [
            {
                "id": "1",
                "title": "Legal Consultation & Feasibility",
                "description": "Engage Wyoming DAO LLC specialist counsel.",
                "status": "completed",
                "details": [
                    "Reviewed Wyoming DAO LLC Act",
                    "Identified required operating agreement amendments",
                ],
                "documents": ["wyoming_dao_llc_requirements.pdf"],
            },
            {
                "id": "2",
                "title": "Operating Agreement Drafting",
                "description": "Draft new DAO-compliant Operating Agreement.",
                "status": "in_progress",
                "details": ["Template acquired", "Pending customization for RMI tokenomics"],
                "documents": [],
            },
            {
                "id": "3",
                "title": "Articles of Organization Amendment",
                "description": "File amendment with Wyoming Secretary of State.",
                "status": "pending",
                "details": ["Requires signed operating agreement first", "Filing fee: $100"],
                "documents": [],
            },
            {
                "id": "4",
                "title": "EIN Update & IRS Notification",
                "description": "Update Employer Identification Number records.",
                "status": "pending",
                "details": ["Form 8822-B may be required"],
                "documents": [],
            },
            {
                "id": "5",
                "title": "Banking & Financial Institution Update",
                "description": "Notify existing banking partners.",
                "status": "pending",
                "details": ["Prepare corporate resolution"],
                "documents": [],
            },
        ],
    }


@router.patch("/dao-transition/steps/{step_id}")
async def update_dao_step(request: Request, step_id: str, body: dict = Body(...)):
    """Update a DAO transition step status."""
    await require_admin(request, "config.write", AdminRole.ADMIN)
    return {"success": True, "step_id": step_id, "status": body.get("status")}


@router.post("/content/generate")
async def generate_content(request: Request, body: dict = Body(...)):
    """Generate content for Ghost CMS."""
    await require_admin(request, "content.write", AdminRole.ADMIN)
    content_type = body.get("type", "twitter")
    topic = body.get("topic", "")
    body.get("tone", "professional")

    mock_content = {
        "twitter": f"🚨 {topic} is a critical topic for crypto security. Always verify contracts before interacting. #RMI #CryptoSecurity",
        "thread": f"🧡 Thread: {topic}\n\n1/ The crypto space is evolving rapidly, and {topic} represents a major shift.\n\n2/ Here's what you need to know to stay safe and informed.\n\n3/ Always DYOR and use tools like RMI to verify before you trust.",
        "longform": f"# {topic}: A Comprehensive Guide\n\n## Introduction\n{topic} has become a focal point in the Web3 ecosystem. This guide breaks down the essentials.\n\n## Key Takeaways\n- Always verify smart contracts\n- Use multi-sig wallets for treasury management\n- Stay updated with RMI intelligence feeds\n\n## Conclusion\nSecurity is not an afterthought; it's the foundation.",
        "newsletter": f"Subject: Weekly Intel: {topic}\n\nHey team,\n\nThis week's focus is on {topic}. We've seen a 40% increase in related activity. Here's what you need to know...",
    }

    return {
        "content": mock_content.get(content_type, mock_content["twitter"]),
        "metadata": {
            "word_count": len(mock_content.get(content_type, "").split()),
            "estimated_read_time": "1m" if content_type == "twitter" else "3m",
            "hashtags": ["#RMI", "#CryptoSecurity", "#Web3"],
        },
    }


@router.post("/wallets/generate")
async def generate_wallet(request: Request, body: dict = Body(...)):
    """Generate a new wallet for a specific chain."""
    await require_admin(request, "wallets.write", AdminRole.ADMIN)
    chain = body.get("chain", "ethereum")

    import secrets

    if chain == "solana":
        address = "NewSol" + secrets.token_hex(20)
        private_key = secrets.token_hex(32) + "solana_mock_pk"
    else:
        address = "0x" + secrets.token_hex(20)
        private_key = "0x" + secrets.token_hex(32)

    return {
        "id": f"wallet_{secrets.token_hex(8)}",
        "chain": chain,
        "address": address,
        "private_key": private_key,
        "created_at": datetime.utcnow().strftime("%Y-%m-%d"),
        "label": f"New {chain.capitalize()} Wallet",
    }


@router.post("/contracts/generate")
async def generate_contract(request: Request, body: dict = Body(...)):
    """Generate a smart contract template."""
    await require_admin(request, "contracts.write", AdminRole.ADMIN)
    contract_type = body.get("type", "erc20")
    chain = body.get("chain", "ethereum")
    name = body.get("name", "MyToken")
    symbol = body.get("symbol", "MTK")

    templates = {
        "erc20": f'// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nimport "@openzeppelin/contracts/token/ERC20/ERC20.sol";\nimport "@openzeppelin/contracts/access/Ownable.sol";\n\ncontract {name} is ERC20, Ownable {{\n    constructor() ERC20("{name}", "{symbol}") Ownable(msg.sender) {{\n        _mint(msg.sender, 1000000 * 10 ** decimals());\n    }}\n\n    function mint(address to, uint256 amount) public onlyOwner {{\n        _mint(to, amount);\n    }}\n}}',
        "erc721": f'// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nimport "@openzeppelin/contracts/token/ERC721/ERC721.sol";\nimport "@openzeppelin/contracts/access/Ownable.sol";\n\ncontract {name}NFT is ERC721, Ownable {{\n    uint256 private _nextTokenId;\n\n    constructor() ERC721("{name}", "{symbol}") Ownable(msg.sender) {{}}\n\n    function safeMint(address to) public onlyOwner {{\n        uint256 tokenId = _nextTokenId++;\n        _safeMint(to, tokenId);\n    }}\n}}',
        "multisig": '// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract MultiSigWallet {\n    event Deposit(address indexed sender, uint amount);\n    event SubmitTransaction(address indexed owner, uint indexed txIndex);\n    event ConfirmTransaction(address indexed owner, uint indexed txIndex);\n\n    address[] public owners;\n    mapping(address => bool) public isOwner;\n    uint public numConfirmationsRequired;\n\n    struct Transaction {\n        address to;\n        uint value;\n        bytes data;\n        bool executed;\n        uint numConfirmations;\n    }\n\n    mapping(uint => Transaction) public transactions;\n    mapping(uint => mapping(address => bool)) public isConfirmed;\n\n    constructor(address[] memory _owners, uint _numConfirmationsRequired) {\n        require(_owners.length > 0, "Owners required");\n        require(_numConfirmationsRequired > 0 && _numConfirmationsRequired <= _owners.length, "Invalid number of required confirmations");\n\n        for (uint i = 0; i < _owners.length; i++) {\n            address owner = _owners[i];\n            require(owner != address(0), "Invalid owner");\n            require(!isOwner[owner], "Owner not unique");\n            isOwner[owner] = true;\n            owners.push(owner);\n        }\n        numConfirmationsRequired = _numConfirmationsRequired;\n    }\n}',
        "timelock": '// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract TimelockController {\n    uint256 public constant MIN_DELAY = 1 days;\n    uint256 public constant MAX_DELAY = 30 days;\n    uint256 public constant GRACE_PERIOD = 14 days;\n\n    uint256 public delay;\n    mapping(bytes32 => bool) public queuedTransactions;\n\n    event QueueTransaction(bytes32 indexed txHash, address target, uint value, string signature, bytes data, uint eta);\n    event ExecuteTransaction(bytes32 indexed txHash, address target, uint value, string signature, bytes data, uint eta);\n\n    constructor(uint256 delay_) {\n        require(delay_ >= MIN_DELAY, "Timelock::constructor: Delay must exceed minimum delay");\n        require(delay_ <= MAX_DELAY, "Timelock::constructor: Delay must not exceed maximum delay");\n        delay = delay_;\n    }\n}',
        "dao_governor": f'// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nimport "@openzeppelin/contracts/governance/Governor.sol";\nimport "@openzeppelin/contracts/governance/extensions/GovernorSettings.sol";\nimport "@openzeppelin/contracts/governance/extensions/GovernorCountingSimple.sol";\nimport "@openzeppelin/contracts/governance/extensions/GovernorVotes.sol";\nimport "@openzeppelin/contracts/governance/extensions/GovernorVotesQuorumFraction.sol";\nimport "@openzeppelin/contracts/governance/extensions/GovernorTimelockControl.sol";\n\ncontract {name}Governor is Governor, GovernorSettings, GovernorCountingSimple, GovernorVotes, GovernorVotesQuorumFraction, GovernorTimelockControl {{\n    constructor(IVotes _token, TimelockController _timelock)\n        Governor("{name} Governor")\n        GovernorSettings(1 /* 1 block */, 50400 /* 1 week */, 0)\n        GovernorVotes(_token)\n        GovernorVotesQuorumFraction(4)\n        GovernorTimelockControl(_timelock)\n    {{}}\n\n    function votingDelay() public view override(Governor, GovernorSettings) returns (uint256) {{ return super.votingDelay(); }}\n    function votingPeriod() public view override(Governor, GovernorSettings) returns (uint256) {{ return super.votingPeriod(); }}\n    function quorum(uint256 blockNumber) public view override(Governor, GovernorVotesQuorumFraction) returns (uint256) {{ return super.quorum(blockNumber); }}\n    function proposalThreshold() public view override(Governor, GovernorSettings) returns (uint256) {{ return super.proposalThreshold(); }}\n}}',
    }

    return {
        "code": templates.get(contract_type, templates["erc20"]),
        "metadata": {
            "compiler": "solc 0.8.20",
            "optimization": True,
            "runs": 200,
            "license": "MIT",
            "chain": chain,
        },
    }


# ═══════════════════════════════════════════════════════════════
# 13. FILE UPLOADS (DAO Documents, etc.)
# ═══════════════════════════════════════════════════════════════

import uuid

from fastapi import File, UploadFile


@router.post("/upload/document")
async def upload_document(request: Request, file: UploadFile = File(...), step_id: str = ""):
    """Upload a document (e.g., DAO transition PDF) with strict MIME-type validation."""
    await require_admin(request, "config.write", AdminRole.ADMIN)

    upload_dir = "/root/backend/uploads/dao_documents"
    os.makedirs(upload_dir, exist_ok=True)

    # Read first 8 bytes for magic number validation
    file_content = await file.read()
    if len(file_content) < 4:
        raise HTTPException(status_code=400, detail="File is too small or empty")

    magic_bytes = file_content[:4]

    # Validate magic bytes: PDF (%PDF) or DOCX/ZIP (PK\x03\x04)
    is_pdf = magic_bytes == b"%PDF"
    is_docx = magic_bytes == b"PK\x03\x04"

    if not (is_pdf or is_docx):
        raise HTTPException(status_code=400, detail="Invalid file type. Only PDF and DOCX are allowed.")

    ext = ".pdf" if is_pdf else ".docx"
    unique_filename = f"{uuid.uuid4().hex}{ext}"
    file_path = os.path.join(upload_dir, unique_filename)

    with open(file_path, "wb") as f:
        f.write(file_content)

    return {
        "success": True,
        "filename": file.filename,
        "url": f"/api/v1/admin/backend/uploads/dao_documents/{unique_filename}",
        "step_id": step_id,
    }


# ═══════════════════════════════════════════════════════════════
# 14. WALLET BALANCE FETCHING
# ═══════════════════════════════════════════════════════════════

import httpx


@router.post("/wallets/fetch-balances")
async def fetch_wallet_balances(request: Request, body: dict = Body(...)):
    """Fetch real-time balances for a list of wallet addresses with RPC fallback."""
    await require_admin(request, "wallets.read", AdminRole.ADMIN)
    wallets = body.get("wallets", [])

    # RPC Fallback Arrays for resilience against rate limits (429) or downtime
    rpc_fallbacks = {
        "ethereum": [
            "https://eth.llamarpc.com",
            "https://rpc.ankr.com/eth",
            "https://cloudflare-eth.com",
        ],
        "base": [
            "https://mainnet.base.org",
            "https://base.llamarpc.com",
            "https://base.publicnode.com",
        ],
        "arbitrum": [
            "https://arb1.arbitrum.io/rpc",
            "https://arbitrum.llamarpc.com",
            "https://arbitrum.publicnode.com",
        ],
        "polygon": [
            "https://polygon-rpc.com",
            "https://polygon.llamarpc.com",
            "https://polygon.publicnode.com",
        ],
    }

    results = []
    for wallet in wallets:
        address = wallet.get("address", "")
        chain = wallet.get("chain", "ethereum")
        balance = "0.00"

        try:
            if chain in rpc_fallbacks:
                payload = {
                    "jsonrpc": "2.0",
                    "method": "eth_getBalance",
                    "params": [address, "latest"],
                    "id": 1,
                }

                # Try each RPC in the fallback array until one succeeds
                success = False
                for rpc_url in rpc_fallbacks[chain]:
                    try:
                        async with httpx.AsyncClient() as client:
                            res = await client.post(rpc_url, json=payload, timeout=5.0)
                            if res.status_code == 200:
                                res_data = res.json()
                                if "result" in res_data and res_data["result"] != "0x":
                                    wei = int(res_data["result"], 16)
                                    balance = f"{wei / 1e18:.4f}"
                                    success = True
                                    break
                    except Exception:
                        continue  # Try next RPC in the array

                if not success:
                    balance = "Error"
            elif chain == "solana":
                balance = "N/A"
        except Exception:
            balance = "Error"

        results.append(
            {
                "id": wallet.get("id"),
                "address": address,
                "chain": chain,
                "balance": f"{balance} {wallet.get('symbol', 'ETH').upper()}",
            }
        )

    return {"balances": results}


# ═══════════════════════════════════════════════════════════════
# 15. CONTRACT DEPLOYMENT (Testnet)
# ═══════════════════════════════════════════════════════════════


@router.post("/contracts/deploy-testnet")
async def deploy_contract_testnet(request: Request, body: dict = Body(...)):
    """Deploy a contract to testnet (mocked for safety)."""
    await require_admin(request, "contracts.write", AdminRole.ADMIN)

    chain = body.get("chain", "base")
    name = body.get("name", "TestToken")

    import secrets

    mock_tx_hash = "0x" + secrets.token_hex(32)
    mock_address = "0x" + secrets.token_hex(20)

    explorer_url = "https://sepolia.basescan.org"
    if chain == "ethereum":
        explorer_url = "https://sepolia.etherscan.io"
    elif chain == "arbitrum":
        explorer_url = "https://sepolia.arbiscan.io"

    return {
        "success": True,
        "tx_hash": mock_tx_hash,
        "contract_address": mock_address,
        "explorer_url": f"{explorer_url}/address/{mock_address}",
        "message": f"Contract '{name}' deployed to {chain} testnet successfully!",
    }


# ═══════════════════════════════════════════════════════════════
# 16. EMERGENCY PANIC BUTTON
# ═══════════════════════════════════════════════════════════════


@router.post("/emergency-lockdown")
async def emergency_lockdown(request: Request, body: dict = Body(...)):
    """Toggle emergency lockdown mode. Blocks all non-admin traffic."""
    auth = await require_admin(request, "system.write", AdminRole.SUPERADMIN)

    import redis.asyncio as redis_lib

    r = redis_lib.Redis(
        host=os.getenv("REDIS_HOST", "localhost"),
        port=int(os.getenv("REDIS_PORT", "6379")),
        password=os.getenv("REDIS_PASSWORD", ""),
        decode_responses=True,
    )

    is_locked = body.get("locked", True)
    reason = body.get("reason", "Manual lockdown triggered")

    if is_locked:
        await r.setex("rmi:emergency_lockdown", 86400, reason)  # 24h TTL
        logger.warning(f"EMERGENCY LOCKDOWN ACTIVATED by {auth['admin']['email']}: {reason}")
    else:
        await r.delete("rmi:emergency_lockdown")
        logger.info(f"EMERGENCY LOCKDOWN DEACTIVATED by {auth['admin']['email']}")

    return {"success": True, "locked": is_locked, "reason": reason}


@router.get("/emergency-status")
async def emergency_status(request: Request):
    """Check current emergency lockdown status."""
    import redis.asyncio as redis_lib

    r = redis_lib.Redis(
        host=os.getenv("REDIS_HOST", "localhost"),
        port=int(os.getenv("REDIS_PORT", "6379")),
        password=os.getenv("REDIS_PASSWORD", ""),
        decode_responses=True,
    )
    reason = await r.get("rmi:emergency_lockdown")
    return {"locked": reason is not None, "reason": reason or ""}