All files / server routes.ts

0% Statements 0/903
0% Branches 0/303
0% Functions 0/124
0% Lines 0/885

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import type { Express } from "express";
import { type Server } from "http";
import { storage } from "./storage";
import { modelMapStorage } from "./modelMapStorage";
import {
  insertResolutionSchema,
  insertMilestoneSchema,
  insertCheckInSchema,
  insertPromptTestSchema,
  insertPromptTemplateSchema,
  insertUserFavoriteSchema,
  insertTestCaseTemplateSchema,
  insertTestCaseConfigurationSchema,
  insertModelFavoriteSchema,
  insertToolFavoriteSchema,
  insertUseCaseSchema,
  insertModelTestSchema,
} from "@shared/schema";
import { z } from "zod";
import { setupAuth, registerAuthRoutes, isAuthenticated } from "./auth_integrations/auth";
import rateLimit from "express-rate-limit";
import { AIOrchestrator } from "./ai/orchestrator";
import { PromptTester } from "./ai/promptTester";
import type { ModelSelectionStrategy } from "./ai/types";
import { log } from "./index";
import { pool } from "./db";
import { promptTemplateSeeds } from "./ai/promptTemplateSeeds";
import { db } from "./db";
import { users } from "@shared/schema";
import { eq } from "drizzle-orm";
 
// Middleware to check if user is admin
async function isAdmin(req: any, res: any, next: any) {
  try {
    const userId = req.user?.claims?.sub;
    if (!userId) {
      return res.status(401).json({ error: "Unauthorized" });
    }
 
    const [user] = await db.select().from(users).where(eq(users.id, userId)).limit(1);
    
    if (!user || user.role !== "admin") {
      return res.status(403).json({ error: "Forbidden: Admin access required" });
    }
 
    next();
  } catch (error) {
    log(`Admin check failed: ${error}`);
    res.status(500).json({ error: "Failed to verify admin status" });
  }
}
 
// Middleware to track API performance metrics
function apiMetricsMiddleware(req: any, res: any, next: any) {
  const startTime = Date.now();
  
  // Store original end function
  const originalEnd = res.end;
  
  // Override end function to log metrics
  res.end = function(...args: any[]) {
    const responseTime = Date.now() - startTime;
    const userId = req.user?.claims?.sub || null;
    
    // Log the metric asynchronously (don't block response)
    storage.logApiMetric({
      userId,
      endpoint: req.path,
      method: req.method,
      statusCode: res.statusCode,
      responseTimeMs: responseTime,
    }).catch((err) => log(`Failed to log API metric: ${err}`));
    
    // Call original end function
    return originalEnd.apply(res, args);
  };
  
  next();
}
 
export async function registerRoutes(
  httpServer: Server,
  app: Express
): Promise<Server> {
  // Setup authentication (must be before other routes)
  await setupAuth(app);
 
  // Global API rate limiter to prevent abuse across all endpoints
  const apiLimiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15 minutes
    max: 1000, // generous limit for general API usage
    standardHeaders: true,
    legacyHeaders: false,
    message: "Too many requests, please try again later.",
  });
 
  // Apply global rate limiting to all API routes
  app.use("/api", apiLimiter);
  
  // Apply performance tracking to all API routes
  app.use("/api", apiMetricsMiddleware);
 
  // Rate limiter for milestone-related routes to mitigate abuse
  const milestoneLimiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15 minutes
    max: 100, // limit each IP to 100 requests per windowMs
    standardHeaders: true,
    legacyHeaders: false,
  });
  registerAuthRoutes(app);
 
  // Health check endpoint (public, for monitoring)
  app.get("/api/health", async (_req, res) => {
    try {
      // Check database connection with a simple query that doesn't require user context
      await pool.query("SELECT 1");
      res.status(200).json({
        status: "healthy",
        timestamp: new Date().toISOString(),
        database: "connected",
      });
    } catch (error) {
      res.status(503).json({
        status: "unhealthy",
        timestamp: new Date().toISOString(),
        database: "disconnected",
        error: error instanceof Error ? error.message : "Unknown error",
      });
    }
  });
 
  // Get configured OAuth providers (public, for login UI)
  app.get("/api/auth/providers", async (_req, res) => {
    const { getConfiguredProviders } = await import("./auth_integrations/auth/oauthAuth");
    const providers = Array.from(getConfiguredProviders());
    res.json({ providers });
  });
 
  // Resolutions CRUD (protected routes)
  app.get("/api/resolutions", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const resolutions = await storage.getResolutions(userId);
      res.json(resolutions);
    } catch (error) {
      res.status(500).json({ error: "Failed to fetch resolutions" });
    }
  });
 
  app.get("/api/resolutions/:id", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const resolution = await storage.getResolution(req.params.id, userId);
      if (!resolution) {
        return res.status(404).json({ error: "Resolution not found" });
      }
      res.json(resolution);
    } catch (error) {
      res.status(500).json({ error: "Failed to fetch resolution" });
    }
  });
 
  app.post("/api/resolutions", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const parsed = insertResolutionSchema.parse(req.body);
      const resolution = await storage.createResolution({ ...parsed, userId });
      
      // Log activity
      await storage.logUserActivity({
        userId,
        action: "resolution_created",
        entityType: "resolution",
        entityId: resolution.id,
        metadata: JSON.stringify({ title: resolution.title, category: resolution.category }),
      });
      
      res.status(201).json(resolution);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return res.status(400).json({ error: error.errors });
      }
      res.status(500).json({ error: "Failed to create resolution" });
    }
  });
 
  app.patch("/api/resolutions/:id", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const updates = insertResolutionSchema.partial().parse(req.body);
      const resolution = await storage.updateResolution(req.params.id, updates, userId);
      if (!resolution) {
        return res.status(404).json({ error: "Resolution not found" });
      }
      res.json(resolution);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return res.status(400).json({ error: error.errors });
      }
      res.status(500).json({ error: "Failed to update resolution" });
    }
  });
 
  app.delete("/api/resolutions/:id", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const deleted = await storage.deleteResolution(req.params.id, userId);
      if (!deleted) {
        return res.status(404).json({ error: "Resolution not found" });
      }
      res.status(204).send();
    } catch (error) {
      res.status(500).json({ error: "Failed to delete resolution" });
    }
  });
 
  // Milestones CRUD (protected)
  app.get("/api/resolutions/:resolutionId/milestones", milestoneLimiter, isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      // Verify the resolution belongs to the authenticated user
      const resolution = await storage.getResolution(req.params.resolutionId, userId);
      if (!resolution) {
        return res.status(404).json({ error: "Resolution not found" });
      }
      const milestones = await storage.getMilestones(req.params.resolutionId);
      res.json(milestones);
    } catch (error) {
      res.status(500).json({ error: "Failed to fetch milestones" });
    }
  });
 
  app.post("/api/milestones", milestoneLimiter, isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const parsed = insertMilestoneSchema.parse(req.body);
      // Verify the resolution belongs to the authenticated user
      const resolution = await storage.getResolution(parsed.resolutionId, userId);
      if (!resolution) {
        return res.status(403).json({ error: "Unauthorized: Resolution not found or does not belong to user" });
      }
      const milestone = await storage.createMilestone(parsed);
      res.status(201).json(milestone);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return res.status(400).json({ error: error.errors });
      }
      res.status(500).json({ error: "Failed to create milestone" });
    }
  });
 
  app.patch("/api/milestones/:id", milestoneLimiter, isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      // First get the milestone to find its associated resolution
      const existingMilestone = await storage.getMilestone(req.params.id);
      if (!existingMilestone) {
        return res.status(404).json({ error: "Milestone not found" });
      }
      // Verify the resolution belongs to the authenticated user
      const resolution = await storage.getResolution(existingMilestone.resolutionId, userId);
      if (!resolution) {
        return res.status(403).json({ error: "Unauthorized: Resolution does not belong to user" });
      }
      const updates = insertMilestoneSchema.partial().parse(req.body);
      const milestone = await storage.updateMilestone(req.params.id, updates);
      if (!milestone) {
        return res.status(404).json({ error: "Milestone not found" });
      }
      res.json(milestone);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return res.status(400).json({ error: error.errors });
      }
      res.status(500).json({ error: "Failed to update milestone" });
    }
  });
 
  app.delete("/api/milestones/:id", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      // First get the milestone to find its associated resolution
      const existingMilestone = await storage.getMilestone(req.params.id);
      if (!existingMilestone) {
        return res.status(404).json({ error: "Milestone not found" });
      }
      // Verify the resolution belongs to the authenticated user
      const resolution = await storage.getResolution(existingMilestone.resolutionId, userId);
      if (!resolution) {
        return res.status(403).json({ error: "Unauthorized: Resolution does not belong to user" });
      }
      const deleted = await storage.deleteMilestone(req.params.id);
      if (!deleted) {
        return res.status(404).json({ error: "Milestone not found" });
      }
      res.status(204).send();
    } catch (error) {
      res.status(500).json({ error: "Failed to delete milestone" });
    }
  });
 
  // Check-ins (protected)
  app.get("/api/check-ins", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const checkIns = await storage.getCheckIns(userId);
      res.json(checkIns);
    } catch (error) {
      res.status(500).json({ error: "Failed to fetch check-ins" });
    }
  });
 
  app.get("/api/resolutions/:resolutionId/check-ins", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      // Verify the resolution belongs to the authenticated user
      const resolution = await storage.getResolution(req.params.resolutionId, userId);
      if (!resolution) {
        return res.status(404).json({ error: "Resolution not found" });
      }
      const checkIns = await storage.getCheckInsByResolution(req.params.resolutionId);
      res.json(checkIns);
    } catch (error) {
      res.status(500).json({ error: "Failed to fetch check-ins" });
    }
  });
 
  app.post("/api/check-ins", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const parsed = insertCheckInSchema.parse(req.body);
      // Verify the resolution belongs to the authenticated user
      const resolution = await storage.getResolution(parsed.resolutionId, userId);
      if (!resolution) {
        return res.status(403).json({ error: "Unauthorized: Resolution not found or does not belong to user" });
      }
      const checkIn = await storage.createCheckIn(parsed);
 
      // Trigger AI analysis asynchronously (non-blocking)
      if (process.env.AI_ENABLE_ANALYSIS !== "false") {
        const orchestrator = new AIOrchestrator(storage);
        const historicalCheckIns = await storage.getCheckInsByResolution(resolution.id);
 
        orchestrator.analyzeCheckInAsync(
          checkIn.id,
          {
            checkInNote: checkIn.note,
            resolutionContext: {
              title: resolution.title,
              description: resolution.description,
              category: resolution.category,
              currentProgress: resolution.progress,
              targetDate: resolution.targetDate,
            },
            historicalCheckIns: historicalCheckIns.slice(-5).map((c) => ({
              note: c.note,
              date: c.date,
            })),
          },
          (process.env.AI_STRATEGY as ModelSelectionStrategy) || "all"
        );
      }
 
      // Log activity
      await storage.logUserActivity({
        userId,
        action: "check_in_added",
        entityType: "check_in",
        entityId: checkIn.id,
        metadata: JSON.stringify({ resolutionId: parsed.resolutionId }),
      });
 
      res.status(201).json(checkIn);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return res.status(400).json({ error: error.errors });
      }
      res.status(500).json({ error: "Failed to create check-in" });
    }
  });
 
  // AI Insights endpoints
  app.get("/api/check-ins/:checkInId/insights", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const checkIn = await storage.getCheckIn(req.params.checkInId);
 
      if (!checkIn) {
        return res.status(404).json({ error: "Check-in not found" });
      }
 
      // Verify ownership through resolution
      const resolution = await storage.getResolution(checkIn.resolutionId, userId);
      if (!resolution) {
        return res.status(404).json({ error: "Not found" });
      }
 
      const insights = await storage.getAiInsightsByCheckIn(req.params.checkInId);
      res.json(insights);
    } catch (error) {
      res.status(500).json({ error: "Failed to fetch insights" });
    }
  });
 
  // Get model usage statistics for user
  app.get("/api/ai/model-stats", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const stats = await storage.getAiModelUsageStats({ userId });
      res.json(stats);
    } catch (error) {
      res.status(500).json({ error: "Failed to fetch stats" });
    }
  });
 
  // Get aggregated model comparison metrics
  app.get("/api/ai/model-comparison", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const allUsage = await storage.getAiModelUsageStats({ userId });
 
      // Aggregate by model
      const modelGroups = allUsage.reduce((acc, usage) => {
        if (!acc[usage.modelName]) {
          acc[usage.modelName] = [];
        }
        acc[usage.modelName].push(usage);
        return acc;
      }, {} as Record<string, typeof allUsage>);
 
      const comparison = Object.entries(modelGroups).map(([modelName, usages]) => {
        const totalCalls = usages.length;
        const successfulCalls = usages.filter((u) => u.status === "success").length;
        const failedCalls = totalCalls - successfulCalls;
        const avgLatency = usages.reduce((sum, u) => sum + u.latencyMs, 0) / totalCalls;
        const totalCost = usages
          .reduce((sum, u) => sum + parseFloat(u.estimatedCost), 0)
          .toFixed(6);
        const avgTokens = usages.reduce((sum, u) => sum + u.totalTokens, 0) / totalCalls;
 
        return {
          modelName,
          provider: usages[0].provider,
          totalCalls,
          successfulCalls,
          failedCalls,
          successRate: ((successfulCalls / totalCalls) * 100).toFixed(2),
          avgLatency: Math.round(avgLatency),
          totalCost,
          avgTokens: Math.round(avgTokens),
        };
      });
 
      res.json(comparison);
    } catch (error) {
      res.status(500).json({ error: "Failed to fetch comparison" });
    }
  });
 
  // Prompt Testing endpoints
  app.post("/api/prompt-tests", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const parsed = insertPromptTestSchema.parse(req.body);
 
      const promptTest = await storage.createPromptTest({
        ...parsed,
        userId,
      });
 
      // Parse selected models if provided
      const selectedModels = promptTest.selectedModels 
        ? JSON.parse(promptTest.selectedModels) 
        : undefined;
 
      // Run the prompt against selected or all AI models asynchronously
      const tester = new PromptTester(storage);
      tester.testPrompt(
        promptTest.id, 
        {
          prompt: promptTest.prompt,
          systemPrompt: promptTest.systemPrompt || undefined,
        },
        selectedModels
      );
 
      res.status(201).json(promptTest);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return res.status(400).json({ error: error.errors });
      }
      log(`Failed to create prompt test: ${error}`);
      res.status(500).json({ error: "Failed to create prompt test" });
    }
  });
 
  app.get("/api/prompt-tests", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const tests = await storage.getPromptTests(userId);
      res.json(tests);
    } catch (error) {
      log(`Failed to fetch prompt tests: ${error}`);
      res.status(500).json({ error: "Failed to fetch prompt tests" });
    }
  });
 
  app.get("/api/prompt-tests/:id", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const test = await storage.getPromptTest(req.params.id, userId);
 
      if (!test) {
        return res.status(404).json({ error: "Prompt test not found" });
      }
 
      res.json(test);
    } catch (error) {
      log(`Failed to fetch prompt test: ${error}`);
      res.status(500).json({ error: "Failed to fetch prompt test" });
    }
  });
 
  app.get("/api/prompt-tests/:id/results", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const test = await storage.getPromptTest(req.params.id, userId);
 
      if (!test) {
        return res.status(404).json({ error: "Prompt test not found" });
      }
 
      const results = await storage.getPromptTestResults(req.params.id);
      res.json(results);
    } catch (error) {
      log(`Failed to fetch prompt test results: ${error}`);
      res.status(500).json({ error: "Failed to fetch results" });
    }
  });
 
  app.patch("/api/prompt-test-results/:id/rating", isAuthenticated, async (req: any, res) => {
    try {
      const { userRating, userComment } = req.body;
 
      if (userRating !== undefined && (userRating < 1 || userRating > 5)) {
        return res.status(400).json({ error: "Rating must be between 1 and 5" });
      }
 
      const updated = await storage.updatePromptTestResult(req.params.id, {
        userRating,
        userComment,
      });
 
      if (!updated) {
        return res.status(404).json({ error: "Result not found" });
      }
 
      res.json(updated);
    } catch (error) {
      log(`Failed to update rating: ${error}`);
      res.status(500).json({ error: "Failed to update rating" });
    }
  });
 
  app.delete("/api/prompt-tests/:id", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const deleted = await storage.deletePromptTest(req.params.id, userId);
 
      if (!deleted) {
        return res.status(404).json({ error: "Prompt test not found" });
      }
 
      res.status(204).send();
    } catch (error) {
      log(`Failed to delete prompt test: ${error}`);
      res.status(500).json({ error: "Failed to delete prompt test" });
    }
  });
 
  // ============================================
  // MODEL MAP ROUTES
  // ============================================
 
  // AI Models (global catalog)
  app.get("/api/model-map/models", async (_req, res) => {
    try {
      const models = await modelMapStorage.getAiModels();
      res.json(models);
    } catch (error) {
      log(`Failed to fetch AI models: ${error}`);
      res.status(500).json({ error: "Failed to fetch AI models" });
    }
  });
 
  app.get("/api/model-map/models/:id", async (req, res) => {
    try {
      const model = await modelMapStorage.getAiModel(req.params.id);
      if (!model) {
        return res.status(404).json({ error: "Model not found" });
      }
      res.json(model);
    } catch (error) {
      log(`Failed to fetch AI model: ${error}`);
      res.status(500).json({ error: "Failed to fetch AI model" });
    }
  });
 
  // AI Tools (global catalog)
  app.get("/api/model-map/tools", async (_req, res) => {
    try {
      const tools = await modelMapStorage.getAiTools();
      res.json(tools);
    } catch (error) {
      log(`Failed to fetch AI tools: ${error}`);
      res.status(500).json({ error: "Failed to fetch AI tools" });
    }
  });
 
  app.get("/api/model-map/tools/:id", async (req, res) => {
    try {
      const tool = await modelMapStorage.getAiTool(req.params.id);
      if (!tool) {
        return res.status(404).json({ error: "Tool not found" });
      }
      res.json(tool);
    } catch (error) {
      log(`Failed to fetch AI tool: ${error}`);
      res.status(500).json({ error: "Failed to fetch AI tool" });
    }
  });
 
  // User Models (user-specific selections)
  app.get("/api/model-map/user/models", isAuthenticated, async (req: any, res) => {
    try {
      const userId = (req as any).user?.claims?.sub;
      const includeStats = req.query.includeStats === "true";
      const userModels = await modelMapStorage.getUserModels(userId);
 
      if (!includeStats) {
        return res.json(userModels);
      }
 
      // Calculate stats for each model from test results
      const tests = await modelMapStorage.getModelTests(userId);
      const userModelsWithStats = await Promise.all(
        userModels.map(async (um) => {
          // Get all results for this model across all tests
          let modelResults: any[] = [];
          for (const test of tests) {
            const testResults = await modelMapStorage.getModelTestResults(test.id);
            modelResults.push(...testResults.filter(r => r.modelId === um.modelId));
          }
 
          // Calculate stats from completed, rated results
          const ratedResults = modelResults.filter(r =>
            r.status === "completed" && (r.userRating !== null || r.accuracyRating !== null)
          );
 
          const stats = ratedResults.length > 0
            ? {
                testCount: ratedResults.length,
                avgOverall: Math.round(
                  ratedResults.reduce((sum, r) => sum + (r.userRating ?? 0), 0) / ratedResults.length
                ),
                avgAccuracy: Math.round(
                  ratedResults.reduce((sum, r) => sum + (r.accuracyRating ?? 0), 0) / ratedResults.length * 10
                ) / 10,
                avgStyle: Math.round(
                  ratedResults.reduce((sum, r) => sum + (r.styleRating ?? 0), 0) / ratedResults.length * 10
                ) / 10,
              }
            : {
                testCount: 0,
                avgOverall: 0,
                avgAccuracy: 0,
                avgStyle: 0,
              };
 
          return { ...um, stats };
        })
      );
 
      res.json(userModelsWithStats);
    } catch (error) {
      log(`Failed to fetch user models: ${error}`);
      res.status(500).json({ error: "Failed to fetch user models" });
    }
  });
 
  app.post("/api/model-map/user/models", isAuthenticated, async (req: any, res) => {
    try {
      const userId = (req as any).user?.claims?.sub;
      const { modelId, notes } = req.body;
      const userModel = await modelMapStorage.addUserModel({ userId, modelId, notes });
      res.status(201).json(userModel);
    } catch (error) {
      log(`Failed to add user model: ${error}`);
      res.status(500).json({ error: "Failed to add user model" });
    }
  });
 
  app.delete("/api/model-map/user/models/:modelId", isAuthenticated, async (req: any, res) => {
    try {
      const userId = (req as any).user?.claims?.sub;
      const deleted = await modelMapStorage.removeUserModel(userId, req.params.modelId);
      if (!deleted) {
        return res.status(404).json({ error: "User model not found" });
      }
      res.status(204).send();
    } catch (error) {
      log(`Failed to remove user model: ${error}`);
      res.status(500).json({ error: "Failed to remove user model" });
    }
  });
 
  // User Tools (user-specific selections)
  app.get("/api/model-map/user/tools", isAuthenticated, async (req: any, res) => {
    try {
      const userId = (req as any).user?.claims?.sub;
      const includeStats = req.query.includeStats === "true";
      const userTools = await modelMapStorage.getUserTools(userId);
 
      if (!includeStats) {
        return res.json(userTools);
      }
 
      // Calculate stats for each tool from test results
      const tests = await modelMapStorage.getModelTests(userId);
      const userToolsWithStats = await Promise.all(
        userTools.map(async (ut) => {
          // Get all results for this tool across all tests
          let toolResults: any[] = [];
          for (const test of tests) {
            const testResults = await modelMapStorage.getModelTestResults(test.id);
            toolResults.push(...testResults.filter(r => r.toolId === ut.toolId));
          }
 
          // Calculate stats from completed, rated results
          const ratedResults = toolResults.filter(r =>
            r.status === "completed" && (r.userRating !== null || r.accuracyRating !== null)
          );
 
          const stats = ratedResults.length > 0
            ? {
                testCount: ratedResults.length,
                avgOverall: Math.round(
                  ratedResults.reduce((sum, r) => sum + (r.userRating ?? 0), 0) / ratedResults.length
                ),
                avgAccuracy: Math.round(
                  ratedResults.reduce((sum, r) => sum + (r.accuracyRating ?? 0), 0) / ratedResults.length * 10
                ) / 10,
                avgStyle: Math.round(
                  ratedResults.reduce((sum, r) => sum + (r.styleRating ?? 0), 0) / ratedResults.length * 10
                ) / 10,
              }
            : {
                testCount: 0,
                avgOverall: 0,
                avgAccuracy: 0,
                avgStyle: 0,
              };
 
          return { ...ut, stats };
        })
      );
 
      res.json(userToolsWithStats);
    } catch (error) {
      log(`Failed to fetch user tools: ${error}`);
      res.status(500).json({ error: "Failed to fetch user tools" });
    }
  });
 
  app.post("/api/model-map/user/tools", isAuthenticated, async (req: any, res) => {
    try {
      const userId = (req as any).user?.claims?.sub;
      const { toolId, notes } = req.body;
      const userTool = await modelMapStorage.addUserTool({ userId, toolId, notes });
      res.status(201).json(userTool);
    } catch (error) {
      log(`Failed to add user tool: ${error}`);
      res.status(500).json({ error: "Failed to add user tool" });
    }
  });
 
  app.delete("/api/model-map/user/tools/:toolId", isAuthenticated, async (req: any, res) => {
    try {
      const userId = (req as any).user?.claims?.sub;
      const deleted = await modelMapStorage.removeUserTool(userId, req.params.toolId);
      if (!deleted) {
        return res.status(404).json({ error: "User tool not found" });
      }
      res.status(204).send();
    } catch (error) {
      log(`Failed to remove user tool: ${error}`);
      res.status(500).json({ error: "Failed to remove user tool" });
    }
  });
 
  // Use Cases
  app.get("/api/model-map/use-cases", async (req, res) => {
    try {
      const { category, curated } = req.query;
      const filters: { category?: string; isCurated?: boolean } = {};
      if (category && typeof category === "string") {
        filters.category = category;
      }
      if (curated === "true") {
        filters.isCurated = true;
      }
      const useCases = await modelMapStorage.getUseCases(filters);
      res.json(useCases);
    } catch (error) {
      log(`Failed to fetch use cases: ${error}`);
      res.status(500).json({ error: "Failed to fetch use cases" });
    }
  });
 
  app.get("/api/model-map/use-cases/:id", async (req, res) => {
    try {
      const useCase = await modelMapStorage.getUseCase(req.params.id);
      if (!useCase) {
        return res.status(404).json({ error: "Use case not found" });
      }
      res.json(useCase);
    } catch (error) {
      log(`Failed to fetch use case: ${error}`);
      res.status(500).json({ error: "Failed to fetch use case" });
    }
  });
 
  app.post("/api/model-map/use-cases", isAuthenticated, async (req: any, res) => {
    try {
      const userId = (req as any).user?.claims?.sub;
      const validated = insertUseCaseSchema.parse({
        ...req.body,
        authorId: userId,
        isCurated: false,
        isPublic: true,
      });
      const useCase = await modelMapStorage.createUseCase(validated);
      res.status(201).json(useCase);
    } catch (error) {
      log(`Failed to create use case: ${error}`);
      res.status(500).json({ error: "Failed to create use case" });
    }
  });
 
  app.put("/api/model-map/use-cases/:id", isAuthenticated, async (req: any, res) => {
    try {
      const userId = (req as any).user?.claims?.sub;
      const useCase = await modelMapStorage.getUseCase(req.params.id);
      if (!useCase) {
        return res.status(404).json({ error: "Use case not found" });
      }
      if (useCase.authorId !== userId) {
        return res.status(403).json({ error: "Not authorized to edit this use case" });
      }
      const updated = await modelMapStorage.updateUseCase(req.params.id, req.body);
      res.json(updated);
    } catch (error) {
      log(`Failed to update use case: ${error}`);
      res.status(500).json({ error: "Failed to update use case" });
    }
  });
 
  app.delete("/api/model-map/use-cases/:id", isAuthenticated, async (req: any, res) => {
    try {
      const userId = (req as any).user?.claims?.sub;
      const deleted = await modelMapStorage.deleteUseCase(req.params.id, userId);
      if (!deleted) {
        return res.status(404).json({ error: "Use case not found or not authorized" });
      }
      res.status(204).send();
    } catch (error) {
      log(`Failed to delete use case: ${error}`);
      res.status(500).json({ error: "Failed to delete use case" });
    }
  });
 
  // User Use Cases (favorites)
  app.get("/api/model-map/user/use-cases", isAuthenticated, async (req: any, res) => {
    try {
      const userId = (req as any).user?.claims?.sub;
      const userUseCases = await modelMapStorage.getUserUseCases(userId);
      res.json(userUseCases);
    } catch (error) {
      log(`Failed to fetch user use cases: ${error}`);
      res.status(500).json({ error: "Failed to fetch user use cases" });
    }
  });
 
  app.post("/api/model-map/user/use-cases", isAuthenticated, async (req: any, res) => {
    try {
      const userId = (req as any).user?.claims?.sub;
      const { useCaseId } = req.body;
      const userUseCase = await modelMapStorage.addUserUseCase({ userId, useCaseId });
      res.status(201).json(userUseCase);
    } catch (error) {
      log(`Failed to add user use case: ${error}`);
      res.status(500).json({ error: "Failed to add user use case" });
    }
  });
 
  app.delete("/api/model-map/user/use-cases/:useCaseId", isAuthenticated, async (req: any, res) => {
    try {
      const userId = (req as any).user?.claims?.sub;
      const deleted = await modelMapStorage.removeUserUseCase(userId, req.params.useCaseId);
      if (!deleted) {
        return res.status(404).json({ error: "User use case not found" });
      }
      res.status(204).send();
    } catch (error) {
      log(`Failed to remove user use case: ${error}`);
      res.status(500).json({ error: "Failed to remove user use case" });
    }
  });
 
  // Model Tests
  app.get("/api/model-map/tests", isAuthenticated, async (req: any, res) => {
    try {
      const userId = (req as any).user?.claims?.sub;
      const includeResults = req.query.includeResults === "true";
      const tests = await modelMapStorage.getModelTests(userId);
 
      if (includeResults) {
        // Fetch results for each test and include use case info
        const testsWithResults = await Promise.all(
          tests.map(async (test) => {
            const results = await modelMapStorage.getModelTestResults(test.id);
            const useCase = test.useCaseId
              ? await modelMapStorage.getUseCase(test.useCaseId)
              : null;
            return {
              ...test,
              results,
              useCase: useCase ? { category: useCase.category } : null,
            };
          })
        );
        return res.json(testsWithResults);
      }
 
      res.json(tests);
    } catch (error) {
      log(`Failed to fetch model tests: ${error}`);
      res.status(500).json({ error: "Failed to fetch model tests" });
    }
  });
 
  app.get("/api/model-map/tests/:id", isAuthenticated, async (req: any, res) => {
    try {
      const userId = (req as any).user?.claims?.sub;
      const test = await modelMapStorage.getModelTest(req.params.id, userId);
      if (!test) {
        return res.status(404).json({ error: "Model test not found" });
      }
      res.json(test);
    } catch (error) {
      log(`Failed to fetch model test: ${error}`);
      res.status(500).json({ error: "Failed to fetch model test" });
    }
  });
 
  app.post("/api/model-map/tests", isAuthenticated, async (req: any, res) => {
    try {
      const userId = (req as any).user?.claims?.sub;
      const { title, useCaseId, prompt, systemPrompt } = req.body;
 
      // Derive prompt from use case if not provided by client
      let resolvedPrompt = prompt as string | undefined;
      let resolvedSystemPrompt = systemPrompt as string | undefined;
      if (!resolvedPrompt && useCaseId) {
        const useCase = await modelMapStorage.getUseCase(useCaseId);
        if (!useCase) {
          return res.status(400).json({ error: "Invalid useCaseId: use case not found" });
        }
        if (useCase.promptTemplate) {
          resolvedPrompt = useCase.promptTemplate;
        }
      }
 
      const validated = insertModelTestSchema.parse({
        title: title || "Untitled Test",
        useCaseId: useCaseId || null,
        prompt: resolvedPrompt || "",
        systemPrompt: resolvedSystemPrompt || null,
        status: "pending",
      });
 
      const test = await modelMapStorage.createModelTest({
        ...validated,
        userId,
      });
      res.status(201).json(test);
    } catch (error) {
      log(`Failed to create model test: ${error}`);
      res.status(500).json({ error: "Failed to create model test" });
    }
  });
 
  app.delete("/api/model-map/tests/:id", isAuthenticated, async (req: any, res) => {
    try {
      const userId = (req as any).user?.claims?.sub;
      const deleted = await modelMapStorage.deleteModelTest(req.params.id, userId);
      if (!deleted) {
        return res.status(404).json({ error: "Model test not found" });
      }
      res.status(204).send();
    } catch (error) {
      log(`Failed to delete model test: ${error}`);
      res.status(500).json({ error: "Failed to delete model test" });
    }
  });
 
  // Model Test Results
  app.get("/api/model-map/tests/:testId/results", isAuthenticated, async (req: any, res) => {
    try {
      const userId = (req as any).user?.claims?.sub;
      const test = await modelMapStorage.getModelTest(req.params.testId, userId);
      if (!test) {
        return res.status(404).json({ error: "Model test not found" });
      }
      const results = await modelMapStorage.getModelTestResults(req.params.testId);
      res.json(results);
    } catch (error) {
      log(`Failed to fetch model test results: ${error}`);
      res.status(500).json({ error: "Failed to fetch model test results" });
    }
  });
 
  app.post("/api/model-map/tests/:testId/results", isAuthenticated, async (req: any, res) => {
    try {
      const userId = (req as any).user?.claims?.sub;
      const test = await modelMapStorage.getModelTest(req.params.testId, userId);
      if (!test) {
        return res.status(404).json({ error: "Model test not found" });
      }
      const result = await modelMapStorage.createModelTestResult({
        testId: req.params.testId,
        ...req.body,
      });
      res.status(201).json(result);
    } catch (error) {
      log(`Failed to create model test result: ${error}`);
      res.status(500).json({ error: "Failed to create model test result" });
    }
  });
 
  app.patch("/api/model-map/tests/:testId/results/:resultId", isAuthenticated, async (req: any, res) => {
    try {
      const userId = (req as any).user?.claims?.sub;
      const { userRating, userNotes, accuracyRating, styleRating, speedRating, xFactor, status } = req.body;
      const result = await modelMapStorage.updateModelTestResult(req.params.resultId, {
        userRating,
        userNotes,
        accuracyRating,
        styleRating,
        speedRating,
        xFactor,
        status,
      });
      if (!result) {
        return res.status(404).json({ error: "Model test result not found" });
      }
 
      // Get the test and check if all results are completed
      const test = await modelMapStorage.getModelTestById(result.testId);
      if (test) {
        const allResults = await modelMapStorage.getModelTestResults(test.id);
        const allCompleted = allResults.every(r => r.status === "completed" || r.userRating);
 
        // Update test status to completed if all results are done
        if (allCompleted && test.status === "pending") {
          await modelMapStorage.updateModelTest(test.id, { status: "completed" });
        }
 
        // Generate/update recommendations if test has rated results
        if (allCompleted && test.useCaseId) {
          const ratedResults = allResults.filter(r => r.userRating);
          if (ratedResults.length > 0) {
            const useCase = await modelMapStorage.getUseCase(test.useCaseId);
            if (useCase) {
              const avgRating = Math.round(
                ratedResults.reduce((sum, r) => sum + (r.userRating || 0), 0) / ratedResults.length
              );
 
              // Find best model/tool from results
              const bestResult = ratedResults.reduce((best, r) =>
                (r.userRating || 0) > (best.userRating || 0) ? r : best
              );
 
              if (bestResult.modelId) {
                await modelMapStorage.updateRecommendation(
                  userId,
                  useCase.category,
                  bestResult.modelId,
                  avgRating
                );
              }
            }
          }
        }
      }
 
      res.json(result);
    } catch (error) {
      log(`Failed to update model test result: ${error}`);
      res.status(500).json({ error: "Failed to update model test result" });
    }
  });
 
  // Direct test result update endpoint (alternative path)
  app.patch("/api/model-map/test-results/:id", isAuthenticated, async (req: any, res) => {
    try {
      const userId = (req as any).user?.claims?.sub;
      const { userRating, userNotes, accuracyRating, styleRating, speedRating, xFactor, status } = req.body;
      const result = await modelMapStorage.updateModelTestResult(req.params.id, {
        userRating,
        userNotes,
        accuracyRating,
        styleRating,
        speedRating,
        xFactor,
        status,
      });
      if (!result) {
        return res.status(404).json({ error: "Model test result not found" });
      }
 
      // Get the test and check if all results are completed
      const test = await modelMapStorage.getModelTestById(result.testId);
      if (test) {
        const allResults = await modelMapStorage.getModelTestResults(test.id);
        const allCompleted = allResults.every(r => r.status === "completed" || r.userRating);
 
        // Update test status to completed if all results are done
        if (allCompleted && test.status === "pending") {
          await modelMapStorage.updateModelTest(test.id, { status: "completed" });
        }
 
        // Generate/update recommendations if test has rated results
        if (allCompleted && test.useCaseId) {
          const ratedResults = allResults.filter(r => r.userRating);
          if (ratedResults.length > 0) {
            const useCase = await modelMapStorage.getUseCase(test.useCaseId);
            if (useCase) {
              const avgRating = Math.round(
                ratedResults.reduce((sum, r) => sum + (r.userRating || 0), 0) / ratedResults.length
              );
 
              // Find best model/tool from results
              const bestResult = ratedResults.reduce((best, r) =>
                (r.userRating || 0) > (best.userRating || 0) ? r : best
              );
 
              if (bestResult.modelId) {
                await modelMapStorage.updateRecommendation(
                  userId,
                  useCase.category,
                  bestResult.modelId,
                  avgRating
                );
              }
            }
          }
        }
      }
 
      res.json(result);
    } catch (error) {
      log(`Failed to update model test result: ${error}`);
      res.status(500).json({ error: "Failed to update model test result" });
    }
  });
 
  // Model Recommendations
  app.get("/api/model-map/recommendations", isAuthenticated, async (req: any, res) => {
    try {
      const userId = (req as any).user?.claims?.sub;
      const recommendations = await modelMapStorage.getUserRecommendations(userId);
      res.json(recommendations);
    } catch (error) {
      log(`Failed to fetch recommendations: ${error}`);
      res.status(500).json({ error: "Failed to fetch recommendations" });
    }
  });
 
  // ============================================
  // PROMPT TEMPLATE ROUTES (from prompt-playground-enhanced)
  // ============================================
 
  // Prompt Template endpoints
  app.get("/api/prompt-templates", isAuthenticated, async (req: any, res) => {
    try {
      const category = req.query.category as string | undefined;
      const templates = await storage.getPromptTemplates(category);
      res.json(templates);
    } catch (error) {
      log(`Failed to fetch prompt templates: ${error}`);
      res.status(500).json({ error: "Failed to fetch prompt templates" });
    }
  });
 
  app.get("/api/prompt-templates/:id", isAuthenticated, async (req: any, res) => {
    try {
      const template = await storage.getPromptTemplate(req.params.id);
      if (!template) {
        return res.status(404).json({ error: "Template not found" });
      }
      res.json(template);
    } catch (error) {
      log(`Failed to fetch prompt template: ${error}`);
      res.status(500).json({ error: "Failed to fetch template" });
    }
  });
 
  app.post("/api/prompt-templates", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const parsed = insertPromptTemplateSchema.parse(req.body);
      
      const template = await storage.createPromptTemplate({
        ...parsed,
        createdBy: userId,
      });
 
      res.status(201).json(template);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return res.status(400).json({ error: error.errors });
      }
      log(`Failed to create prompt template: ${error}`);
      res.status(500).json({ error: "Failed to create template" });
    }
  });
 
  app.patch("/api/prompt-templates/:id", isAuthenticated, async (req: any, res) => {
    try {
      const updated = await storage.updatePromptTemplate(req.params.id, req.body);
      if (!updated) {
        return res.status(404).json({ error: "Template not found" });
      }
      res.json(updated);
    } catch (error) {
      log(`Failed to update prompt template: ${error}`);
      res.status(500).json({ error: "Failed to update template" });
    }
  });
 
  app.delete("/api/prompt-templates/:id", isAuthenticated, async (req: any, res) => {
    try {
      const deleted = await storage.deletePromptTemplate(req.params.id);
      if (!deleted) {
        return res.status(404).json({ error: "Template not found" });
      }
      res.status(204).send();
    } catch (error) {
      log(`Failed to delete prompt template: ${error}`);
      res.status(500).json({ error: "Failed to delete template" });
    }
  });
 
  // Seed prompt templates (one-time initialization)
  app.post("/api/prompt-templates/seed", isAuthenticated, async (req: any, res) => {
    try {
      const existing = await storage.getPromptTemplates();
      if (existing.length > 0) {
        return res.json({ message: "Templates already seeded", count: existing.length });
      }
 
      const created = await Promise.all(
        promptTemplateSeeds.map(seed => storage.createPromptTemplate(seed))
      );
 
      res.json({ message: "Templates seeded successfully", count: created.length });
    } catch (error) {
      log(`Failed to seed prompt templates: ${error}`);
      res.status(500).json({ error: "Failed to seed templates" });
    }
  });
 
  // User Favorites endpoints
  app.get("/api/favorites", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const favoriteType = req.query.type as string | undefined;
      const favorites = await storage.getUserFavorites(userId, favoriteType);
      res.json(favorites);
    } catch (error) {
      log(`Failed to fetch favorites: ${error}`);
      res.status(500).json({ error: "Failed to fetch favorites" });
    }
  });
 
  app.post("/api/favorites", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const parsed = insertUserFavoriteSchema.parse(req.body);
 
      // Check if already favorited
      const existing = await storage.getFavorite(userId, parsed.favoriteType, parsed.favoriteId);
      if (existing) {
        return res.status(409).json({ error: "Already favorited" });
      }
 
      const favorite = await storage.createFavorite({
        ...parsed,
        userId,
      });
 
      res.status(201).json(favorite);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return res.status(400).json({ error: error.errors });
      }
      log(`Failed to create favorite: ${error}`);
      res.status(500).json({ error: "Failed to create favorite" });
    }
  });
 
  app.delete("/api/favorites/:id", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const deleted = await storage.deleteFavorite(req.params.id, userId);
 
      if (!deleted) {
        return res.status(404).json({ error: "Favorite not found" });
      }
 
      res.status(204).send();
    } catch (error) {
      log(`Failed to delete favorite: ${error}`);
      res.status(500).json({ error: "Failed to delete favorite" });
    }
  });
 
  // Model Map / Analytics endpoint
  app.get("/api/ai/model-map", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      
      // Get all prompt test results for the user
      const tests = await storage.getPromptTests(userId);
      const allResults = await Promise.all(
        tests.map(test => storage.getPromptTestResults(test.id))
      );
 
      // Group by category and model
      const categoryMap: Record<string, Record<string, any[]>> = {};
 
      for (let i = 0; i < tests.length; i++) {
        const test = tests[i];
        const results = allResults[i];
        const category = test.category || "general";
        if (!categoryMap[category]) {
          categoryMap[category] = {};
        }
 
        for (const result of results) {
          if (!categoryMap[category][result.modelName]) {
            categoryMap[category][result.modelName] = [];
          }
          categoryMap[category][result.modelName].push({
            latency: result.latencyMs,
            cost: parseFloat(result.estimatedCost),
            tokens: result.totalTokens,
            rating: result.userRating,
            status: result.status,
          });
        }
      }
 
      // Calculate aggregate stats for each model in each category
      const modelMap = Object.entries(categoryMap).map(([category, models]) => {
        const modelStats = Object.entries(models).map(([modelName, results]) => {
          const successfulResults = results.filter(r => r.status === "success");
          const count = results.length;
          const successCount = successfulResults.length;
          
          if (successCount === 0) {
            return {
              modelName,
              count,
              successRate: 0,
              avgLatency: 0,
              avgCost: 0,
              avgRating: null,
            };
          }
 
          const avgLatency = successfulResults.reduce((sum, r) => sum + r.latency, 0) / successCount;
          const avgCost = successfulResults.reduce((sum, r) => sum + r.cost, 0) / successCount;
          const ratedResults = successfulResults.filter(r => r.rating !== null);
          const avgRating = ratedResults.length > 0
            ? ratedResults.reduce((sum, r) => sum + (r.rating || 0), 0) / ratedResults.length
            : null;
 
          return {
            modelName,
            count,
            successRate: (successCount / count) * 100,
            avgLatency: Math.round(avgLatency),
            avgCost: avgCost.toFixed(6),
            avgRating: avgRating ? avgRating.toFixed(1) : null,
          };
        });
 
        return {
          category,
          models: modelStats,
        };
      });
 
      res.json(modelMap);
    } catch (error) {
      log(`Failed to generate model map: ${error}`);
      res.status(500).json({ error: "Failed to generate model map" });
    }
  });
 
  // Test Case Templates
  app.get("/api/test-case-templates", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const templates = await storage.getTestCaseTemplates(userId);
      res.json(templates);
    } catch (error) {
      log(`Failed to get test case templates: ${error}`);
      res.status(500).json({ error: "Failed to get test case templates" });
    }
  });
 
  app.get("/api/test-case-templates/:id", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const template = await storage.getTestCaseTemplate(req.params.id);
      if (!template) {
        return res.status(404).json({ error: "Template not found" });
      }
      // Non-built-in templates should only be accessible to their creator
      if (!template.isBuiltIn && template.userId !== userId) {
        return res.status(404).json({ error: "Template not found" });
      }
      res.json(template);
    } catch (error) {
      log(`Failed to get test case template: ${error}`);
      res.status(500).json({ error: "Failed to get test case template" });
    }
  });
 
  app.post("/api/test-case-templates", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const parsed = insertTestCaseTemplateSchema.parse({
        ...req.body,
        isBuiltIn: false, // User-created templates are never built-in
        userId,
      });
 
      const template = await storage.createTestCaseTemplate(parsed);
      res.status(201).json(template);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return res.status(400).json({ error: error.errors });
      }
      log(`Failed to create test case template: ${error}`);
      res.status(500).json({ error: "Failed to create test case template" });
    }
  });
 
  app.patch("/api/test-case-templates/:id", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const parsed = insertTestCaseTemplateSchema.partial().parse(req.body);
      const updated = await storage.updateTestCaseTemplate(req.params.id, parsed, userId);
 
      if (!updated) {
        return res.status(404).json({ error: "Template not found or unauthorized" });
      }
 
      res.json(updated);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return res.status(400).json({ error: error.errors });
      }
      log(`Failed to update test case template: ${error}`);
      res.status(500).json({ error: "Failed to update test case template" });
    }
  });
 
  app.delete("/api/test-case-templates/:id", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const deleted = await storage.deleteTestCaseTemplate(req.params.id, userId);
 
      if (!deleted) {
        return res.status(404).json({ error: "Template not found or unauthorized" });
      }
 
      res.status(204).send();
    } catch (error) {
      log(`Failed to delete test case template: ${error}`);
      res.status(500).json({ error: "Failed to delete test case template" });
    }
  });
 
  // Test Case Configurations
  app.get("/api/test-case-configurations/:promptTestId", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      // Verify user owns the prompt test
      const test = await storage.getPromptTest(req.params.promptTestId, userId);
      if (!test) {
        return res.status(404).json({ error: "Test configuration not found" });
      }
      const config = await storage.getTestCaseConfiguration(req.params.promptTestId);
      res.json(config);
    } catch (error) {
      log(`Failed to get test case configuration: ${error}`);
      res.status(500).json({ error: "Failed to get test case configuration" });
    }
  });
 
  app.post("/api/test-case-configurations", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const parsed = insertTestCaseConfigurationSchema.parse(req.body);
      // Verify user owns the prompt test before creating config
      const test = await storage.getPromptTest(parsed.promptTestId, userId);
      if (!test) {
        return res.status(404).json({ error: "Prompt test not found" });
      }
      const config = await storage.createTestCaseConfiguration(parsed);
      res.status(201).json(config);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return res.status(400).json({ error: error.errors });
      }
      log(`Failed to create test case configuration: ${error}`);
      res.status(500).json({ error: "Failed to create test case configuration" });
    }
  });
 
  // Model Favorites
  app.get("/api/model-favorites", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const favorites = await storage.getModelFavorites(userId);
      res.json(favorites);
    } catch (error) {
      log(`Failed to get model favorites: ${error}`);
      res.status(500).json({ error: "Failed to get model favorites" });
    }
  });
 
  app.post("/api/model-favorites", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const parsed = insertModelFavoriteSchema.parse({ ...req.body, userId });
      const favorite = await storage.createModelFavorite(parsed);
      res.status(201).json(favorite);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return res.status(400).json({ error: error.errors });
      }
      log(`Failed to create model favorite: ${error}`);
      res.status(500).json({ error: "Failed to create model favorite" });
    }
  });
 
  app.delete("/api/model-favorites/:id", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const deleted = await storage.deleteModelFavorite(req.params.id, userId);
 
      if (!deleted) {
        return res.status(404).json({ error: "Favorite not found" });
      }
 
      res.status(204).send();
    } catch (error) {
      log(`Failed to delete model favorite: ${error}`);
      res.status(500).json({ error: "Failed to delete model favorite" });
    }
  });
 
  // Tool Favorites
  app.get("/api/tool-favorites", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const favorites = await storage.getToolFavorites(userId);
      res.json(favorites);
    } catch (error) {
      log(`Failed to get tool favorites: ${error}`);
      res.status(500).json({ error: "Failed to get tool favorites" });
    }
  });
 
  app.post("/api/tool-favorites", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const parsed = insertToolFavoriteSchema.parse({ ...req.body, userId });
      const favorite = await storage.createToolFavorite(parsed);
      res.status(201).json(favorite);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return res.status(400).json({ error: error.errors });
      }
      log(`Failed to create tool favorite: ${error}`);
      res.status(500).json({ error: "Failed to create tool favorite" });
    }
  });
 
  app.delete("/api/tool-favorites/:id", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const deleted = await storage.deleteToolFavorite(req.params.id, userId);
 
      if (!deleted) {
        return res.status(404).json({ error: "Favorite not found" });
      }
 
      res.status(204).send();
    } catch (error) {
      log(`Failed to delete tool favorite: ${error}`);
      res.status(500).json({ error: "Failed to delete tool favorite" });
    }
  });
 
  // Model Performance Analytics
  app.get("/api/model-analytics", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      
      // Get all prompt test results for this user
      const tests = await storage.getPromptTests(userId);
      const allResults = await Promise.all(
        tests.map(test => storage.getPromptTestResults(test.id))
      );
      
      // Flatten results
      const results = allResults.flat();
      
      // Group by model and calculate stats
      const modelStats = new Map<string, {
        modelName: string;
        provider: string;
        totalTests: number;
        successCount: number;
        avgLatency: number;
        totalCost: number;
        avgRating: number;
        ratingCount: number;
      }>();
      
      for (const result of results) {
        const key = `${result.provider}-${result.modelName}`;
        const stats = modelStats.get(key) || {
          modelName: result.modelName,
          provider: result.provider,
          totalTests: 0,
          successCount: 0,
          avgLatency: 0,
          totalCost: 0,
          avgRating: 0,
          ratingCount: 0,
        };
        
        stats.totalTests++;
        if (result.status === 'success') stats.successCount++;
        stats.avgLatency += result.latencyMs;
        const estimatedCost = Number.parseFloat(result.estimatedCost);
        if (!Number.isNaN(estimatedCost)) {
          stats.totalCost += estimatedCost;
        }
        if (result.userRating) {
          stats.avgRating += result.userRating;
          stats.ratingCount++;
        }
        
        modelStats.set(key, stats);
      }
      
      // Calculate averages
      const analytics = Array.from(modelStats.values()).map(stats => ({
        ...stats,
        avgLatency: stats.totalTests > 0 ? Math.round(stats.avgLatency / stats.totalTests) : 0,
        successRate: stats.totalTests > 0 ? (stats.successCount / stats.totalTests) * 100 : 0,
        avgRating: stats.ratingCount > 0 ? stats.avgRating / stats.ratingCount : 0,
      }));
      
      res.json(analytics);
    } catch (error) {
      log(`Failed to get model analytics: ${error}`);
      res.status(500).json({ error: "Failed to get model analytics" });
    }
  });
 
  // Analytics routes (protected)
  
  // Get analytics stats - user can see their own, admins can see all
  app.get("/api/analytics/stats", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const [user] = await db.select().from(users).where(eq(users.id, userId)).limit(1);
      
      // If user is admin and no specific user requested, show global stats
      const targetUserId = user?.role === "admin" && !req.query.userId ? undefined : userId;
      
      const stats = await storage.getAnalyticsStats(targetUserId);
      res.json(stats);
    } catch (error) {
      log(`Failed to fetch analytics stats: ${error}`);
      res.status(500).json({ error: "Failed to fetch analytics stats" });
    }
  });
 
  // Get user activity log
  app.get("/api/analytics/activity", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const limit = req.query.limit ? parseInt(req.query.limit as string) : 50;
      
      const activities = await storage.getUserActivityLog(userId, limit);
      res.json(activities);
    } catch (error) {
      log(`Failed to fetch activity log: ${error}`);
      res.status(500).json({ error: "Failed to fetch activity log" });
    }
  });
 
  // Get API performance metrics
  app.get("/api/analytics/performance", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const [user] = await db.select().from(users).where(eq(users.id, userId)).limit(1);
      
      // Only admins can see all performance metrics, regular users see their own
      const targetUserId = user?.role === "admin" && !req.query.userId ? undefined : userId;
      
      const metrics = await storage.getApiMetrics({ userId: targetUserId });
      res.json(metrics);
    } catch (error) {
      log(`Failed to fetch performance metrics: ${error}`);
      res.status(500).json({ error: "Failed to fetch performance metrics" });
    }
  });
 
  // Get page view statistics
  app.get("/api/analytics/pageviews", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const [user] = await db.select().from(users).where(eq(users.id, userId)).limit(1);
      
      // Only admins can see all page views, regular users see their own
      const targetUserId = user?.role === "admin" && !req.query.userId ? undefined : userId;
      
      const stats = await storage.getPageViewStats({ userId: targetUserId });
      res.json(stats);
    } catch (error) {
      log(`Failed to fetch page view stats: ${error}`);
      res.status(500).json({ error: "Failed to fetch page view stats" });
    }
  });
 
  // Log page view (called from frontend)
  app.post("/api/analytics/pageview", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const { path, referrer } = req.body;
      
      await storage.logPageView({
        userId,
        path,
        referrer: referrer || null,
        userAgent: req.get('user-agent') || null,
      });
      
      res.status(201).json({ success: true });
    } catch (error) {
      log(`Failed to log page view: ${error}`);
      res.status(500).json({ error: "Failed to log page view" });
    }
  });
 
  // Get current user info including role
  app.get("/api/user/me", isAuthenticated, async (req: any, res) => {
    try {
      const userId = req.user.claims.sub;
      const [user] = await db.select().from(users).where(eq(users.id, userId)).limit(1);
      
      if (!user) {
        return res.status(404).json({ error: "User not found" });
      }
      
      res.json(user);
    } catch (error) {
      log(`Failed to fetch user info: ${error}`);
      res.status(500).json({ error: "Failed to fetch user info" });
    }
  });
 
  return httpServer;
}