All files / src/highlights highlights.ts

13.03% Statements 156/1197
72.22% Branches 26/36
60% Functions 6/10
13.03% Lines 156/1197

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 16351x 1x 1x               1x 1x 1x   1x 1x 1x 1x 1x                                                                                                                                   1x 22x 22x 22x 22x 22x   22x 22x 22x 22x 22x         22x               22x 22x 22x   22x     22x 25x 25x 22x   22x 23x 23x 1x 1x   22x 22x 22x 19x 23x 3x 3x   19x 19x 19x 19x 19x 19x     19x     19x 19x     19x 19x 18x 17x 23x 2x 2x 2x 2x 2x 2x 2x     19x 19x 19x 19x 19x 23x           23x   22x 22x                   22x 19x 19x 19x 19x 19x 7x 7x     19x 1x 1x     19x 5x   5x 2x 2x 5x   19x 19x 1x 1x 1x 1x 1x 19x 18x 18x 18x 18x 18x 18x 19x 19x         22x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x   2x 2x         22x 19x 19x 19x 19x 19x   19x 19x 19x 19x 19x 19x   19x 19x 22x           1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
import * as vscode from "vscode";
import * as path from "node:path";
import * as fs from "node:fs";
import type {
    StructuredTooltip,
    TooltipAlert,
    TooltipOperation,
    TooltipFinding,
} from "@dataflint/mcp-server";
import { HighlightCodeLineData } from "./highlights-models";
import { findActualLine } from "./highlights-utils";
import { DataFlintFileDecorationProvider } from "./file-decoration-provider";
import { DataFlintDiagnosticProvider } from "./diagnostic-provider";
import { DataFlintTreeViewProvider } from "../tree-view";
import { buildReportData } from "./report-utils";
import { calculateSeverityCounts } from "./severity-utils";
import { Logger } from "../logger";
import { OperationQueue } from "../operation-queue";
import {
    ExtensionCommands,
    HighlightIntent,
    ObjectIntent,
} from "../extension-commands";
 
// ============================================================================
// DECORATION TYPES - Visual styling for highlights (NOT faded like CodeLens)
// ============================================================================
 
/**
 * Create decoration types for different severity levels
 * Includes gutter icons for high visibility
 */
function createDecorationTypes(extensionPath: string) {
    const logger = Logger.getInstance();
    const iconsPath = path.join(extensionPath, "resources", "icons");
 
    logger.debug(`Creating decoration types with icons from: ${iconsPath}`);
 
    // Hotspot line - fire icon 🔥 with DataFlint red-orange (#FA6A0D)
    const hotspotDecoration = vscode.window.createTextEditorDecorationType({
        backgroundColor: "rgba(250, 106, 13, 0.15)",
        borderWidth: "0 0 0 3px",
        borderStyle: "solid",
        borderColor: "#FA6A0D",
        isWholeLine: true,
        overviewRulerColor: "#FA6A0D",
        overviewRulerLane: vscode.OverviewRulerLane.Left,
        gutterIconPath: vscode.Uri.file(path.join(iconsPath, "hotspot.svg")),
        gutterIconSize: "75%",
    });
 
    // Warning line - warning triangle ⚠️ with DataFlint orange (#FF8900)
    const warningDecoration = vscode.window.createTextEditorDecorationType({
        backgroundColor: "rgba(255, 137, 0, 0.12)",
        borderWidth: "0 0 0 3px",
        borderStyle: "solid",
        borderColor: "#FF8900",
        isWholeLine: true,
        overviewRulerColor: "#FF8900",
        overviewRulerLane: vscode.OverviewRulerLane.Left,
        gutterIconPath: vscode.Uri.file(path.join(iconsPath, "warning.svg")),
        gutterIconSize: "75%",
    });
 
    // Info line - info circle 📊 with DataFlint mint green (#A3F5B9)
    const infoDecoration = vscode.window.createTextEditorDecorationType({
        backgroundColor: "rgba(163, 245, 185, 0.12)",
        borderWidth: "0 0 0 3px",
        borderStyle: "solid",
        borderColor: "#A3F5B9",
        isWholeLine: true,
        overviewRulerColor: "#A3F5B9",
        overviewRulerLane: vscode.OverviewRulerLane.Left,
        gutterIconPath: vscode.Uri.file(path.join(iconsPath, "info.svg")),
        gutterIconSize: "75%",
    });
 
    return {
        hotspot: hotspotDecoration,
        warning: warningDecoration,
        info: infoDecoration,
    };
}
 
export class DataFlintCodeLensProvider implements vscode.CodeLensProvider {
    private getHighlights: () => HighlightCodeLineData[];
    private _onDidChangeCodeLenses: vscode.EventEmitter<void> =
        new vscode.EventEmitter<void>();
    public readonly onDidChangeCodeLenses: vscode.Event<void> =
        this._onDidChangeCodeLenses.event;
 
    constructor(getHighlights: () => HighlightCodeLineData[]) {
        this.getHighlights = getHighlights;
        const logger = Logger.getInstance();
        logger.debug("DataFlintCodeLensProvider initialized");
    }
 
    /**
     * Trigger refresh of code lenses
     */
    public refresh(): void {
        this._onDidChangeCodeLenses.fire();
    }
 
    /**
     * Provide code lenses for the given document
     * Returns CodeLens items per highlight (header + Fix It action)
     */
    public provideCodeLenses(document: vscode.TextDocument): vscode.CodeLens[] {
        const logger = Logger.getInstance();
        const codeLenses: vscode.CodeLens[] = [];
 
        const allHighlights = this.getHighlights();
 
        // Filter highlights for this document
        const documentHighlights = allHighlights.filter((highlight) => {
            const highlightUri = vscode.Uri.file(highlight.filePath);
            return highlightUri.fsPath === document.uri.fsPath;
        });
 
        for (const highlight of documentHighlights) {
            try {
                if (!highlight.text) {
                    continue;
                }
 
                const actualLineIndex = findActualLine(document, highlight);
                if (
                    actualLineIndex === null ||
                    actualLineIndex >= document.lineCount
                ) {
                    continue;
                }
 
                const range = new vscode.Range(
                    actualLineIndex,
                    0,
                    actualLineIndex,
                    0
                );
 
                // Get the actual code text for context
                const lineText = document.lineAt(actualLineIndex).text.trim();
 
                // Add main header CodeLens
                const headerLens = this.createHeaderCodeLens(highlight, range);
                codeLenses.push(headerLens);
 
                // Add 🔧 Fix It CodeLens (for issues that need fixing)
                if (
                    highlight.isHotspot ||
                    (highlight.alertCount && highlight.alertCount > 0) ||
                    (highlight.findingCount && highlight.findingCount > 0)
                ) {
                    const fixLens = this.createFixItCodeLens(
                        highlight,
                        range,
                        lineText
                    );
                    codeLenses.push(fixLens);
                }
 
                // Add 🚩 Report Issue CodeLens (always available for feedback)
                const reportLens = this.createReportIssueCodeLens(
                    highlight,
                    range
                );
                codeLenses.push(reportLens);
            } catch (error) {
                logger.error(
                    `Error creating code lens for line ${highlight.codeLine}`,
                    error
                );
            }
        }
 
        return codeLenses;
    }
 
    /**
     * Create a single CodeLens header for a highlight
     *
     * Display format: "🔵Q1 45% ⏱️ 🔥 | 🔴 Critical Issue (+3)"
     * - queryPrefix + metrics + hotspot indicator
     * - top prioritized item (finding or alert)
     * - (+N) for additional items (clickable for tooltip)
     */
    private createHeaderCodeLens(
        highlight: HighlightCodeLineData,
        range: vscode.Range
    ): vscode.CodeLens {
        let headerText = highlight.text || "";
        if (highlight.queryPrefix) {
            headerText = `${highlight.queryPrefix} ${headerText}`;
        }
 
        // Add hotspot indicator
        if (highlight.isHotspot) {
            headerText = `${headerText} 🔥`;
        }
 
        // Add prioritized item display (most important alert/finding)
        if (highlight.topItemDisplay) {
            headerText = `${headerText} | ${highlight.topItemDisplay}`;
            // Add overflow indicator - clickable to show tooltip with all items
            if (highlight.additionalCount && highlight.additionalCount > 0) {
                headerText = `${headerText} (+${highlight.additionalCount})`;
            }
        }
 
        const codeLens = new vscode.CodeLens(range);
        if (highlight.url) {
            codeLens.command = {
                title: headerText,
                command: ExtensionCommands.OPEN_URL,
                arguments: [highlight.url],
            };
        } else {
            codeLens.command = {
                title: headerText,
                command: "dataflint-copilot.showPartInfo",
                arguments: [headerText],
            };
        }
        return codeLens;
    }
 
    /**
     * Create a Fix It CodeLens that opens AI assistance
     */
    private createFixItCodeLens(
        highlight: HighlightCodeLineData,
        range: vscode.Range,
        codeText: string
    ): vscode.CodeLens {
        const codeLens = new vscode.CodeLens(range);
 
        // Build the fix intent
        const fixIntent: HighlightIntent = {
            type: "fix",
            scope: "line",
            jobId: highlight.jobId ?? 0,
            filePath: highlight.filePath,
            codeLine: highlight.codeLine,
            codeText: codeText,
            target: {
                displayText: highlight.text || "Performance issue",
                isHotspot: highlight.isHotspot || false,
                alerts: highlight.structuredTooltip?.alerts,
                operations: highlight.structuredTooltip?.operations,
                findings: highlight.structuredTooltip?.findings,
            },
            sqlIds:
                highlight.sql_ids ||
                (highlight.sql_id ? [highlight.sql_id] : []),
            nodeIds: highlight.node_ids || [],
            url: highlight.url,
        };
 
        codeLens.command = {
            title: "🔧 Fix It",
            command: ExtensionCommands.FIX_HIGHLIGHT,
            arguments: [fixIntent],
        };
 
        return codeLens;
    }
 
    /**
     * Create a Report Issue CodeLens for user feedback
     */
    private createReportIssueCodeLens(
        highlight: HighlightCodeLineData,
        range: vscode.Range
    ): vscode.CodeLens {
        const codeLens = new vscode.CodeLens(range);
        const reportData = buildReportData(highlight);
 
        codeLens.command = {
            title: "$(report) Report",
            tooltip: "Report an issue with this highlight",
            command: ExtensionCommands.REPORT_HIGHLIGHT_ISSUE,
            arguments: [reportData],
        };
 
        return codeLens;
    }
}
 
// ============================================================================
// DECORATION MANAGER - Handles visual decorations for highlights
// ============================================================================
 
class HighlightDecorationManager {
    private decorationTypes: ReturnType<typeof createDecorationTypes>;
    private fixIconDataUri: string;
    private explainIconDataUri: string;
    private reportIconDataUri: string;
 
    constructor(extensionPath: string) {
        this.decorationTypes = createDecorationTypes(extensionPath);
 
        // Load SVG icons as base64 data URIs for use in tooltips
        const iconsPath = path.join(extensionPath, "resources", "icons");
        this.fixIconDataUri = this.loadSvgAsDataUri(
            path.join(iconsPath, "fix.svg")
        );
        this.explainIconDataUri = this.loadSvgAsDataUri(
            path.join(iconsPath, "explain.svg")
        );
        this.reportIconDataUri = this.loadSvgAsDataUri(
            path.join(iconsPath, "report.svg")
        );
    }
 
    /**
     * Load an SVG file and convert it to a base64 data URI
     */
    private loadSvgAsDataUri(svgPath: string): string {
        try {
            const svgContent = fs.readFileSync(svgPath, "utf8");
            const base64 = Buffer.from(svgContent).toString("base64");
            return `data:image/svg+xml;base64,${base64}`;
        } catch (error) {
            Logger.getInstance().error(`Failed to load SVG icon: ${svgPath}`);
            return "";
        }
    }
 
    /**
     * Generate HTML for Fix/Explain/Report action links with custom icons
     */
    private buildActionLinks(
        fixUri: string,
        explainUri: string,
        isBold: boolean = false,
        reportUri?: string
    ): string {
        const fixText = isBold ? "<b>Fix It</b>" : "Fix";
        const explainText = isBold ? "<b>Explain It</b>" : "Explain";
        let html =
            `<a href="${fixUri}"><img src="${this.fixIconDataUri}" width="14" height="14" style="vertical-align: middle;"> ${fixText}</a>` +
            ` | ` +
            `<a href="${explainUri}"><img src="${this.explainIconDataUri}" width="14" height="14" style="vertical-align: middle;"> ${explainText}</a>`;
 
        if (reportUri) {
            html += ` | <a href="${reportUri}"><img src="${this.reportIconDataUri}" width="14" height="14" style="vertical-align: middle;"> Report</a>`;
        }
 
        return html;
    }
 
    /**
     * Build a report issue command URI for a highlight
     */
    private buildReportUri(highlight: HighlightCodeLineData): string {
        const reportData = buildReportData(highlight);
        return vscode.Uri.parse(
            `command:${ExtensionCommands.REPORT_HIGHLIGHT_ISSUE}?${encodeURIComponent(JSON.stringify(reportData))}`
        ).toString();
    }
 
    /**
     * Apply decorations to a text editor based on highlights
     * Colored border = visual indicator to hover for details
     */
    public applyDecorations(
        editor: vscode.TextEditor,
        highlights: HighlightCodeLineData[]
    ): void {
        const logger = Logger.getInstance();
        const document = editor.document;
 
        logger.debug(
            `applyDecorations called for ${document.uri.fsPath} with ${highlights.length} total highlights`
        );
 
        // Filter highlights for this document
        const documentHighlights = highlights.filter((h) => {
            const uri = vscode.Uri.file(h.filePath);
            const match = uri.fsPath === document.uri.fsPath;
            if (!match) {
                logger.debug(
                    `  Highlight path mismatch: ${h.filePath} vs ${document.uri.fsPath}`
                );
            }
            return match;
        });
 
        logger.debug(
            `Found ${documentHighlights.length} highlights for this document`
        );
 
        // Group by severity
        const hotspotRanges: vscode.DecorationOptions[] = [];
        const warningRanges: vscode.DecorationOptions[] = [];
        const infoRanges: vscode.DecorationOptions[] = [];
 
        for (const highlight of documentHighlights) {
            const actualLine = findActualLine(document, highlight);
            if (actualLine === null || actualLine >= document.lineCount) {
                logger.debug(
                    `  Skipping highlight at line ${highlight.codeLine} - actual line not found or out of range`
                );
                continue;
            }
 
            const line = document.lineAt(actualLine);
            const range = line.range;
            const codeText = line.text.trim();
 
            // Build rich hover tooltip with Fix It action
            const hoverMarkdown = this.buildHoverMarkdown(highlight, codeText);
 
            const decorationOptions: vscode.DecorationOptions = {
                range,
                hoverMessage: hoverMarkdown,
            };
 
            // Categorize by severity/hotspot
            const severity = highlight.isHotspot
                ? "hotspot"
                : highlight.alertCount && highlight.alertCount > 0
                  ? "warning"
                  : "info";
            logger.debug(
                `  Line ${actualLine}: severity=${severity}, isHotspot=${highlight.isHotspot}, alertCount=${highlight.alertCount}`
            );
 
            if (highlight.isHotspot) {
                hotspotRanges.push(decorationOptions);
            } else if (highlight.alertCount && highlight.alertCount > 0) {
                warningRanges.push(decorationOptions);
            } else {
                infoRanges.push(decorationOptions);
            }
        }
 
        // Apply decorations
        editor.setDecorations(this.decorationTypes.hotspot, hotspotRanges);
        editor.setDecorations(this.decorationTypes.warning, warningRanges);
        editor.setDecorations(this.decorationTypes.info, infoRanges);
 
        logger.debug(
            `Applied decorations: ${hotspotRanges.length} hotspot, ${warningRanges.length} warning, ${infoRanges.length} info`
        );
    }
 
    /**
     * Build hover markdown from structured tooltip data.
     * Falls back to server-computed markdown if structured data unavailable.
     */
    private buildHoverMarkdown(
        highlight: HighlightCodeLineData,
        codeText?: string
    ): vscode.MarkdownString {
        const md = new vscode.MarkdownString();
        md.isTrusted = true;
        md.supportHtml = true;
        md.supportThemeIcons = true;
 
        // Prefer structured tooltip for flexible rendering
        if (highlight.structuredTooltip) {
            this.renderStructuredTooltip(
                md,
                highlight.structuredTooltip,
                highlight,
                codeText
            );
        } else if (highlight.tooltip) {
            // Fallback to server-computed markdown tooltip
            md.appendMarkdown(highlight.tooltip);
        } else {
            // Fallback: basic tooltip if server didn't provide one
            const icon = highlight.isHotspot
                ? "🔥"
                : highlight.alertCount
                  ? "⚠️"
                  : "📊";
            md.appendMarkdown(
                `${icon} ${highlight.text || "Spark Analysis"}\n\n`
            );
 
            if (highlight.url) {
                md.appendMarkdown(`→ Click to view in Spark History Server`);
            }
        }
 
        // Add Fix It and Explain It actions for issues that need attention
        if (
            highlight.isHotspot ||
            (highlight.alertCount && highlight.alertCount > 0) ||
            (highlight.findingCount && highlight.findingCount > 0)
        ) {
            // Build the fix intent for the command
            const fixIntent: HighlightIntent = {
                type: "fix",
                scope: "line",
                jobId: highlight.jobId || 0,
                filePath: highlight.filePath,
                codeLine: highlight.codeLine,
                codeText: codeText,
                target: {
                    displayText: highlight.text || "Performance issue",
                    isHotspot: highlight.isHotspot || false,
                    alerts: highlight.structuredTooltip?.alerts,
                    operations: highlight.structuredTooltip?.operations,
                    findings: highlight.structuredTooltip?.findings,
                },
                sqlIds:
                    highlight.sql_ids ||
                    (highlight.sql_id ? [highlight.sql_id] : []),
                nodeIds: highlight.node_ids || [],
                url: highlight.url,
            };
 
            // Create command URI for the Fix It action
            const fixCommandUri = vscode.Uri.parse(
                `command:${ExtensionCommands.FIX_HIGHLIGHT}?${encodeURIComponent(JSON.stringify(fixIntent))}`
            );
 
            // Build explain intent for the Explain It action
            const explainIntent: HighlightIntent = {
                type: "explain",
                scope: "line",
                jobId: highlight.jobId || 0,
                filePath: highlight.filePath,
                codeLine: highlight.codeLine,
                codeText: codeText,
                target: {
                    displayText: highlight.text || "Performance issue",
                    isHotspot: highlight.isHotspot || false,
                    alerts: highlight.structuredTooltip?.alerts,
                    operations: highlight.structuredTooltip?.operations,
                    findings: highlight.structuredTooltip?.findings,
                },
                sqlIds:
                    highlight.sql_ids ||
                    (highlight.sql_id ? [highlight.sql_id] : []),
                nodeIds: highlight.node_ids || [],
                url: highlight.url,
            };
 
            // Create command URI for the Explain It action
            const explainCommandUri = vscode.Uri.parse(
                `command:${ExtensionCommands.EXPLAIN_HIGHLIGHT}?${encodeURIComponent(JSON.stringify(explainIntent))}`
            );
 
            // Create command URI for the Report Issue action
            const reportUri = this.buildReportUri(highlight);
 
            md.appendMarkdown(`\n\n---\n\n`);
            md.appendMarkdown(
                this.buildActionLinks(
                    fixCommandUri.toString(),
                    explainCommandUri.toString(),
                    true,
                    reportUri
                )
            );
        }
 
        return md;
    }
 
    /**
     * Clear all decorations from an editor
     */
    public clearDecorations(editor: vscode.TextEditor): void {
        editor.setDecorations(this.decorationTypes.hotspot, []);
        editor.setDecorations(this.decorationTypes.warning, []);
        editor.setDecorations(this.decorationTypes.info, []);
    }
 
    /**
     * Build object intent URI for Fix/Explain actions on specific tooltip items
     */
    private buildObjectIntentUri(
        scope: "alert" | "operation" | "finding",
        clickedObject: TooltipAlert | TooltipOperation | TooltipFinding,
        intentType: "fix" | "explain",
        highlight: HighlightCodeLineData,
        st: StructuredTooltip,
        codeText?: string
    ): string {
        const intent: ObjectIntent = {
            type: intentType,
            scope: scope,
            jobId: highlight.jobId || 0,
            filePath: highlight.filePath,
            codeLine: highlight.codeLine,
            codeText: codeText,
            target: {
                displayText: highlight.text || "Performance issue",
                isHotspot: highlight.isHotspot || false,
                alerts: st.alerts,
                operations: st.operations,
                findings: st.findings,
            },
            sqlIds:
                highlight.sql_ids ||
                (highlight.sql_id ? [highlight.sql_id] : []),
            nodeIds: highlight.node_ids || [],
            url: highlight.url,
            clickedObject: clickedObject,
        };
        const command =
            intentType === "fix"
                ? ExtensionCommands.FIX_HIGHLIGHT
                : ExtensionCommands.EXPLAIN_HIGHLIGHT;
        return `command:${command}?${encodeURIComponent(JSON.stringify(intent))}`;
    }
 
    /**
     * Render tooltip header with title and optional reason
     */
    private renderTooltipHeader(
        md: vscode.MarkdownString,
        st: StructuredTooltip,
        highlight: HighlightCodeLineData
    ): void {
        const reportUri = this.buildReportUri(highlight);
        md.appendMarkdown(`**${st.header.title}**`);
        md.appendMarkdown(
            ` <a href="${reportUri}" title="Report an issue with this highlight"><img src="${this.reportIconDataUri}" width="12" height="12" style="vertical-align: middle; opacity: 0.7;"></a>\n\n`
        );
        if (st.header.reason) {
            md.appendMarkdown(`**Why:** ${st.header.reason}\n\n`);
        }
    }
 
    /**
     * Render tooltip summary for multi-operation highlights
     */
    private renderTooltipSummary(
        md: vscode.MarkdownString,
        st: StructuredTooltip
    ): void {
        if (st.summary) {
            md.appendMarkdown(
                `${st.summary.operationCount} operations across ${st.summary.queryCount} queries\n\n`
            );
        }
    }
 
    /**
     * Render failed queries section
     */
    private renderTooltipFailedQueries(
        md: vscode.MarkdownString,
        st: StructuredTooltip
    ): void {
        if (st.failedQueries.length > 0) {
            md.appendMarkdown("**❌ Failed Queries:**\n\n");
            for (const fq of st.failedQueries) {
                md.appendMarkdown(
                    `- **SqlQuery ${fq.sqlId}**: ${fq.description}\n`
                );
            }
            md.appendMarkdown("\n");
        }
    }
 
    /**
     * Render alerts section with Fix/Explain links
     */
    private renderTooltipAlerts(
        md: vscode.MarkdownString,
        st: StructuredTooltip,
        highlight: HighlightCodeLineData,
        codeText?: string
    ): void {
        if (st.alerts.length > 0) {
            md.appendMarkdown("**⚠️ Alerts:**\n\n");
            for (const alert of st.alerts) {
                const fixUri = this.buildObjectIntentUri(
                    "alert",
                    alert,
                    "fix",
                    highlight,
                    st,
                    codeText
                );
                const explainUri = this.buildObjectIntentUri(
                    "alert",
                    alert,
                    "explain",
                    highlight,
                    st,
                    codeText
                );
                md.appendMarkdown(`- **${alert.title}** (${alert.severity})`);
                md.appendMarkdown(
                    ` — ${this.buildActionLinks(fixUri, explainUri)}\n`
                );
                md.appendMarkdown(`  - ${alert.message}\n`);
                if (alert.suggestion) {
                    md.appendMarkdown(`  - 💡 _${alert.suggestion}_\n`);
                }
            }
            md.appendMarkdown("\n");
        }
    }
 
    /**
     * Render operations section with Fix/Explain links for hotspots
     */
    private renderTooltipOperations(
        md: vscode.MarkdownString,
        st: StructuredTooltip,
        highlight: HighlightCodeLineData,
        codeText?: string
    ): void {
        if (st.operations.length > 0) {
            md.appendMarkdown("**Operations:**\n\n");
            for (const op of st.operations) {
                const hot = op.isHotspot ? "🔥" : "";
                const failed = op.isFailed ? "❌ " : "";
                const queryDesc = op.queryDescription
                    ? `: _${op.queryDescription}_`
                    : "";
 
                if (op.isHotspot || op.isFailed) {
                    const fixUri = this.buildObjectIntentUri(
                        "operation",
                        op,
                        "fix",
                        highlight,
                        st,
                        codeText
                    );
                    const explainUri = this.buildObjectIntentUri(
                        "operation",
                        op,
                        "explain",
                        highlight,
                        st,
                        codeText
                    );
                    md.appendMarkdown(
                        `- ${failed}**SqlQuery ${op.sqlId}**${queryDesc}`
                    );
                    md.appendMarkdown(
                        ` — ${this.buildActionLinks(fixUri, explainUri)}\n`
                    );
                } else {
                    md.appendMarkdown(
                        `- ${failed}**SqlQuery ${op.sqlId}**${queryDesc}\n`
                    );
                }
                md.appendMarkdown(
                    `  - ${op.nodeName} | ${op.durationPct.toFixed(0)}%${hot}\n`
                );
                if (op.metricsLine) {
                    md.appendMarkdown(`  - ${op.metricsLine}\n`);
                }
            }
            md.appendMarkdown("\n");
        }
    }
 
    /**
     * Render AI findings section with Fix/Explain links
     */
    private renderTooltipFindings(
        md: vscode.MarkdownString,
        st: StructuredTooltip,
        highlight: HighlightCodeLineData,
        codeText?: string
    ): void {
        if (st.findings.length > 0) {
            md.appendMarkdown("**💡 AI Findings:**\n\n");
            const typeIcons: Record<string, string> = {
                critical: "🔴",
                warning: "⚠️",
                hint: "💡",
                insight: "📊",
                context: "ℹ️",
            };
            for (const f of st.findings) {
                const icon = typeIcons[f.type] || "💡";
                const fixUri = this.buildObjectIntentUri(
                    "finding",
                    f,
                    "fix",
                    highlight,
                    st,
                    codeText
                );
                const explainUri = this.buildObjectIntentUri(
                    "finding",
                    f,
                    "explain",
                    highlight,
                    st,
                    codeText
                );
                const header = f.title || f.message || "Finding";
                md.appendMarkdown(`- ${icon} **${header}**`);
                md.appendMarkdown(
                    ` — ${this.buildActionLinks(fixUri, explainUri)}\n`
                );
                if (f.message && f.message !== f.title) {
                    md.appendMarkdown(`  - ${f.message}\n`);
                }
                if (f.suggestion) {
                    md.appendMarkdown(`  - 💡 _${f.suggestion}_\n`);
                }
                if (f.estimatedImpact) {
                    md.appendMarkdown(`  - 📈 _${f.estimatedImpact}_\n`);
                }
                if (f.codeSnippet) {
                    md.appendMarkdown(`\n\`\`\`\n${f.codeSnippet}\n\`\`\`\n`);
                }
            }
            md.appendMarkdown("\n");
        }
    }
 
    /**
     * Render tooltip footer with deep link
     */
    private renderTooltipFooter(
        md: vscode.MarkdownString,
        st: StructuredTooltip
    ): void {
        md.appendMarkdown("---\n");
        if (st.footer?.deepLinkUrl) {
            md.appendMarkdown(`*${st.footer.deepLinkText}*`);
        } else {
            md.appendMarkdown(
                "*Click CodeLens to open in Spark History Server*"
            );
        }
    }
 
    /**
     * Render structured tooltip data into MarkdownString.
     * Provides flexible, extension-controlled rendering of tooltip sections.
     * Includes per-object Fix/Explain action links.
     */
    private renderStructuredTooltip(
        md: vscode.MarkdownString,
        st: StructuredTooltip,
        highlight: HighlightCodeLineData,
        codeText?: string
    ): void {
        this.renderTooltipHeader(md, st, highlight);
        this.renderTooltipSummary(md, st);
        this.renderTooltipFailedQueries(md, st);
        this.renderTooltipAlerts(md, st, highlight, codeText);
        this.renderTooltipOperations(md, st, highlight, codeText);
        this.renderTooltipFindings(md, st, highlight, codeText);
        this.renderTooltipFooter(md, st);
    }
 
    /**
     * Dispose all decoration types
     */
    public dispose(): void {
        this.decorationTypes.hotspot.dispose();
        this.decorationTypes.warning.dispose();
        this.decorationTypes.info.dispose();
    }
}
 
/** Callback type for clearing mapping hashes when source files change */
export type OnFileChangedCallback = (jobIds: number[]) => void;
 
export class DataFlintHighlights {
    private codeLensProvider: DataFlintCodeLensProvider;
    private decorationManager: HighlightDecorationManager;
    private fileDecorationProvider: DataFlintFileDecorationProvider;
    private diagnosticProvider: DataFlintDiagnosticProvider;
    private treeViewProvider: DataFlintTreeViewProvider | null = null;
    private fileDecorationDisposable: vscode.Disposable;
    private codeLensDisposable: vscode.Disposable | null = null;
    private fileWatcherDisposable: vscode.Disposable | null = null;
    private editorChangeDisposable: vscode.Disposable | null = null;
    private currentHighlightData: HighlightCodeLineData[] = [];
    private clearedHighlights: HighlightCodeLineData[] | null = null;
    private fileWatchers: Map<string, vscode.FileSystemWatcher> = new Map();
    private refreshTimer: NodeJS.Timeout | null = null;
    private operationQueue = new OperationQueue("DataFlintHighlights");
 
    // Query filtering state
    private allHighlightsCache: HighlightCodeLineData[] = [];
    private activeQueryFilter: Set<number> | null = null; // null = show all
    private statusBarItem: vscode.StatusBarItem | null = null;
 
    // Callback for cache invalidation when source files change
    private onFileChangedCallback: OnFileChangedCallback | null = null;
 
    constructor(extensionPath: string) {
        const logger = Logger.getInstance();
        this.codeLensProvider = new DataFlintCodeLensProvider(
            () => this.currentHighlightData
        );
        this.decorationManager = new HighlightDecorationManager(extensionPath);
        this.fileDecorationProvider = new DataFlintFileDecorationProvider();
        this.diagnosticProvider = new DataFlintDiagnosticProvider();
        this.fileDecorationDisposable =
            vscode.window.registerFileDecorationProvider(
                this.fileDecorationProvider
            );
        this.registerProviders();
        this.createStatusBarItem();
        this.registerEditorChangeListener();
        logger.info("DataFlintHighlights initialized");
    }
 
    /**
     * Set callback for when source files with highlights change.
     * Used to invalidate mapping hashes in MCP state.
     */
    public setOnFileChangedCallback(callback: OnFileChangedCallback): void {
        this.onFileChangedCallback = callback;
    }
 
    /**
     * Set tree view provider for automatic refresh on highlight changes
     */
    public setTreeViewProvider(provider: DataFlintTreeViewProvider): void {
        this.treeViewProvider = provider;
    }
 
    /**
     * Refresh the file decorations from the current cached highlights.
     * Used by the refresh command.
     */
    public refreshFileDecorations(): void {
        this.fileDecorationProvider.refresh(this.allHighlightsCache);
    }
 
    /**
     * Listen for editor changes to apply decorations
     */
    private registerEditorChangeListener(): void {
        // Apply decorations when active editor changes
        this.editorChangeDisposable = vscode.window.onDidChangeActiveTextEditor(
            (editor) => {
                if (editor) {
                    this.applyDecorationsToEditor(editor);
                }
            }
        );
 
        // Apply to currently active editor
        if (vscode.window.activeTextEditor) {
            this.applyDecorationsToEditor(vscode.window.activeTextEditor);
        }
    }
 
    /**
     * Apply decorations to a specific editor
     */
    private applyDecorationsToEditor(editor: vscode.TextEditor): void {
        this.decorationManager.applyDecorations(
            editor,
            this.currentHighlightData
        );
    }
 
    /**
     * Apply decorations to all visible editors
     */
    private applyDecorationsToAllEditors(): void {
        for (const editor of vscode.window.visibleTextEditors) {
            this.applyDecorationsToEditor(editor);
        }
    }
 
    /**
     * Create status bar item for query filter indicator
     */
    private createStatusBarItem(): void {
        this.statusBarItem = vscode.window.createStatusBarItem(
            vscode.StatusBarAlignment.Right,
            100
        );
        this.statusBarItem.command =
            "dataflint-copilot.filterHighlightsByQuery";
        this.updateStatusBar();
    }
 
    /**
     * Update status bar to show current filter state with severity counts
     */
    private updateStatusBar(): void {
        if (!this.statusBarItem) {
            return;
        }
 
        const uniqueQueries = this.getUniqueQueries();
        if (uniqueQueries.length === 0) {
            this.statusBarItem.hide();
            return;
        }
 
        // Calculate severity counts from all cached highlights
        const severityCounts = calculateSeverityCounts(this.allHighlightsCache);
 
        // Build severity badge string
        const severityBadges: string[] = [];
        if (severityCounts.hotspot > 0) {
            severityBadges.push(`🔥${severityCounts.hotspot}`);
        }
        if (severityCounts.warning > 0) {
            severityBadges.push(`⚠️${severityCounts.warning}`);
        }
        if (severityCounts.info > 0) {
            severityBadges.push(`📊${severityCounts.info}`);
        }
        const severityText =
            severityBadges.length > 0 ? ` ${severityBadges.join(" ")}` : "";
 
        if (this.activeQueryFilter === null) {
            this.statusBarItem.text = `$(filter) Q${uniqueQueries.length}${severityText}`;
            this.statusBarItem.tooltip = `DataFlint: ${this.allHighlightsCache.length} issues\n${severityCounts.hotspot} hotspots, ${severityCounts.warning} alerts, ${severityCounts.info} findings\nClick to filter by specific queries`;
        } else {
            const filterCount = this.activeQueryFilter.size;
            this.statusBarItem.text = `$(filter-filled) Q${[...this.activeQueryFilter].join(",")}${severityText}`;
            this.statusBarItem.tooltip = `DataFlint: Filtering ${filterCount}/${uniqueQueries.length} queries\n${severityCounts.hotspot} hotspots, ${severityCounts.warning} alerts, ${severityCounts.info} findings\nClick to change query filter`;
        }
        this.statusBarItem.show();
    }
 
    /**
     * Get all unique query IDs from cached highlights
     */
    public getUniqueQueries(): number[] {
        const querySet = new Set<number>();
        for (const h of this.allHighlightsCache) {
            if (h.sql_ids) {
                h.sql_ids.forEach((id) => querySet.add(id));
            } else if (h.sql_id !== undefined) {
                querySet.add(h.sql_id);
            }
        }
        return [...querySet].sort((a, b) => a - b);
    }
 
    /**
     * Filter highlights by query IDs
     * @param queryIds - Set of query IDs to show, or null to show all
     */
    public async filterByQueries(queryIds: Set<number> | null): Promise<void> {
        const logger = Logger.getInstance();
        this.activeQueryFilter = queryIds;
 
        if (queryIds === null) {
            // Show all highlights
            this.currentHighlightData = [...this.allHighlightsCache];
            logger.info("Showing all highlights");
        } else {
            // Filter to highlights that include any of the selected queries
            this.currentHighlightData = this.allHighlightsCache.filter((h) => {
                const highlightQueries =
                    h.sql_ids || (h.sql_id !== undefined ? [h.sql_id] : []);
                return highlightQueries.some((id) => queryIds.has(id));
            });
            logger.info(
                `Filtered to ${this.currentHighlightData.length} highlights for queries: ${[...queryIds].join(", ")}`
            );
        }
 
        this.updateStatusBar();
        this.refreshEditorSurfaces();
    }
 
    /**
     * Show quick pick to select queries for filtering
     */
    public async showQueryFilterPicker(): Promise<void> {
        const uniqueQueries = this.getUniqueQueries();
 
        if (uniqueQueries.length === 0) {
            vscode.window.showInformationMessage(
                "No highlights with query information available"
            );
            return;
        }
 
        // Build quick pick items with query colors
        const QUERY_COLORS = ["🔵", "🟢", "🟠", "🟣", "🟡", "🔴", "⚪", "🟤"];
        const items: vscode.QuickPickItem[] = [
            {
                label: "$(filter) Show All Queries",
                description: `All ${uniqueQueries.length} queries`,
                picked: this.activeQueryFilter === null,
            },
            { label: "", kind: vscode.QuickPickItemKind.Separator },
            ...uniqueQueries.map((id) => {
                const color = QUERY_COLORS[id % QUERY_COLORS.length];
                const highlightCount = this.allHighlightsCache.filter((h) =>
                    (h.sql_ids || [h.sql_id]).includes(id)
                ).length;
                return {
                    label: `${color} Query ${id}`,
                    description: `${highlightCount} highlight${highlightCount !== 1 ? "s" : ""}`,
                    picked: this.activeQueryFilter?.has(id) ?? false,
                };
            }),
        ];
 
        const selected = await vscode.window.showQuickPick(items, {
            placeHolder: "Select queries to display",
            canPickMany: true,
            title: "Filter Highlights by Query",
        });
 
        if (!selected) {
            return; // User cancelled
        }
 
        // Check if "Show All" was selected
        const showAll = selected.some((item) =>
            item.label.includes("Show All")
        );
        if (showAll || selected.length === 0) {
            await this.filterByQueries(null);
            return;
        }
 
        // Extract query IDs from selection
        const selectedIds = new Set<number>();
        for (const item of selected) {
            const match = item.label.match(/Query (\d+)/);
            if (match) {
                selectedIds.add(parseInt(match[1], 10));
            }
        }
 
        if (selectedIds.size > 0) {
            await this.filterByQueries(selectedIds);
        }
    }
 
    /**
     * Register the CodeLens and Hover providers
     */
    private registerProviders(): void {
        // Register for all file types that might contain DataFlint annotations
        const documentSelector: vscode.DocumentSelector = [
            { language: "python" },
            { language: "scala" },
            { language: "java" },
            { language: "javascript" },
            { language: "typescript" },
            { pattern: "**/*.{py,scala,java,js,ts,sql}" },
        ];
 
        this.codeLensDisposable = vscode.languages.registerCodeLensProvider(
            documentSelector,
            this.codeLensProvider
        );
 
        // Listen to text document changes for better position tracking
        this.fileWatcherDisposable = vscode.workspace.onDidChangeTextDocument(
            (e) => {
                // Find highlights in this document
                const highlightsInDoc = this.currentHighlightData.filter(
                    (h) =>
                        vscode.Uri.file(h.filePath).fsPath ===
                        e.document.uri.fsPath
                );
 
                if (highlightsInDoc.length > 0) {
                    // Invalidate mapping hashes for affected jobs
                    this.invalidateMappingHashesForFile(highlightsInDoc);
 
                    // Debounce the refresh to avoid too many updates
                    this.debounceRefresh();
                }
            }
        );
    }
 
    /**
     * Invalidate mapping hashes for jobs with highlights in a changed file.
     * This ensures cache is cleared when source code changes.
     */
    private invalidateMappingHashesForFile(
        highlightsInFile: HighlightCodeLineData[]
    ): void {
        if (!this.onFileChangedCallback) {
            return;
        }
 
        // Collect unique job IDs from highlights in this file
        const jobIds = new Set<number>();
        for (const h of highlightsInFile) {
            if (h.jobId !== undefined) {
                jobIds.add(h.jobId);
            }
        }
 
        if (jobIds.size > 0) {
            const logger = Logger.getInstance();
            logger.debug(
                `File changed, invalidating mapping hashes for jobs: ${[...jobIds].join(", ")}`
            );
            this.onFileChangedCallback([...jobIds]);
        }
    }
 
    private debounceRefresh(): void {
        if (this.refreshTimer) {
            clearTimeout(this.refreshTimer);
        }
        this.refreshTimer = setTimeout(() => {
            this.refreshEditorSurfaces();
        }, 500); // Wait 500ms after last change
    }
 
    /**
     * Setup file watchers for tracked documents
     */
    private setupFileWatcher(filePath: string): void {
        const logger = Logger.getInstance();
 
        // Don't create duplicate watchers
        if (this.fileWatchers.has(filePath)) {
            return;
        }
 
        const uri = vscode.Uri.file(filePath);
        const watcher = vscode.workspace.createFileSystemWatcher(uri.fsPath);
 
        // Refresh highlights when file changes
        watcher.onDidChange(() => {
            logger.debug(`File changed: ${filePath}, refreshing highlights`);
            this.debounceRefresh();
        });
 
        this.fileWatchers.set(filePath, watcher);
    }
 
    /**
     * Refresh data-driven UI surfaces (no file access required).
     * These can display immediately when highlight data is available.
     */
    private refreshDataSurfaces(): void {
        this.updateStatusBar();
        this.fileDecorationProvider.refresh(this.allHighlightsCache);
        this.diagnosticProvider.refresh(this.allHighlightsCache);
        this.treeViewProvider?.refresh(this.allHighlightsCache);
    }
 
    /**
     * Refresh editor-dependent UI surfaces (requires files to be accessible).
     */
    private refreshEditorSurfaces(): void {
        this.codeLensProvider.refresh();
        this.applyDecorationsToAllEditors();
    }
 
    /**
     * Refresh all UI surfaces from current highlight data.
     * This is the single entry point for updating all visual feedback.
     */
    private refreshAllSurfaces(): void {
        const logger = Logger.getInstance();
        logger.debug(
            `Refreshing all UI surfaces with ${this.currentHighlightData.length} highlights`
        );
 
        this.refreshDataSurfaces();
        this.refreshEditorSurfaces();
 
        logger.debug("All UI surfaces refreshed");
    }
 
    public async create(highlightData: HighlightCodeLineData[]): Promise<void> {
        return this.operationQueue.enqueue("create", () =>
            this._create(highlightData)
        );
    }
 
    private async _create(
        highlightData: HighlightCodeLineData[]
    ): Promise<void> {
        const logger = Logger.getInstance();
        try {
            // Update caches
            this.allHighlightsCache = [...highlightData];
            this.activeQueryFilter = null;
            this.currentHighlightData = [...highlightData];
 
            // Phase 1: Refresh data surfaces immediately (tree view appears instantly)
            this.refreshDataSurfaces();
 
            // Setup file watchers for all files with highlights
            const uniqueFiles = new Set(highlightData.map((h) => h.filePath));
            uniqueFiles.forEach((filePath) => this.setupFileWatcher(filePath));
 
            // Open files in parallel to trigger CodeLens display
            const openPromises = [...uniqueFiles].map(async (filePath) => {
                const isOpen = vscode.workspace.textDocuments.some(
                    (doc) => doc.uri.fsPath === vscode.Uri.file(filePath).fsPath
                );
                if (!isOpen) {
                    try {
                        await vscode.workspace.openTextDocument(filePath);
                    } catch (error) {
                        logger.error(`Error opening file ${filePath}:`, error);
                    }
                }
            });
            await Promise.allSettled(openPromises);
 
            // Phase 2: Refresh editor surfaces after files are open
            this.refreshEditorSurfaces();
 
            logger.info(
                `Successfully created ${highlightData.length} highlights`
            );
        } catch (error) {
            logger.error("Error adding highlights:", error);
            throw error;
        }
    }
 
    public async toggle(): Promise<void> {
        return this.operationQueue.enqueue("toggle", () => this._toggle());
    }
 
    private async _toggle(): Promise<void> {
        const logger = Logger.getInstance();
        try {
            if (this.currentHighlightData.length > 0) {
                // Highlights are active, clear them
                this._clear();
                logger.info("Highlights cleared");
                vscode.window.showInformationMessage(
                    "DataFlint highlights cleared"
                );
            } else if (this.clearedHighlights) {
                // Highlights are cleared but we have stored ones, restore them
                await this._restore();
                vscode.window.showInformationMessage(
                    "DataFlint highlights restored"
                );
            } else {
                // No highlights to toggle
                vscode.window.showInformationMessage(
                    "No DataFlint highlights to toggle"
                );
            }
        } catch (error) {
            logger.error("Error toggling highlights:", error);
            vscode.window.showErrorMessage(
                `Failed to toggle highlights: ${error}`
            );
        }
    }
 
    public clear(): void {
        this.operationQueue.enqueue("clear", async () => this._clear());
    }
 
    private _clear(): void {
        const logger = Logger.getInstance();
        if (this.currentHighlightData.length > 0) {
            // Store current highlights for potential restoration
            this.clearedHighlights = [...this.currentHighlightData];
        }
 
        this.currentHighlightData = [];
        this.codeLensProvider.refresh();
 
        // Clear decorations from all visible editors
        for (const editor of vscode.window.visibleTextEditors) {
            this.decorationManager.clearDecorations(editor);
        }
 
        // Clear file decorations
        this.fileDecorationProvider.clear();
 
        // Clear diagnostics (Problems panel)
        this.diagnosticProvider.clear();
 
        // Clear tree view
        if (this.treeViewProvider) {
            this.treeViewProvider.clear();
        }
 
        logger.info("All highlights and decorations cleared");
    }
 
    public async restore(): Promise<void> {
        return this.operationQueue.enqueue("restore", () => this._restore());
    }
 
    private async _restore(): Promise<void> {
        const logger = Logger.getInstance();
        if (!this.clearedHighlights) {
            return;
        }
 
        try {
            // Restore the highlights from the stored data
            await this._create(this.clearedHighlights);
            logger.info(`Restored ${this.clearedHighlights.length} highlights`);
 
            // Clear the stored cleared highlights since they are now active
            this.clearedHighlights = null;
        } catch (error) {
            logger.error("Error restoring highlights:", error);
            throw error;
        }
    }
 
    /**
     * Show a Quick Pick with all issues in the current file or specified file.
     * Issues are grouped by severity (Hotspots → Alerts → Findings).
     * Selecting an issue navigates to that line in the file.
     *
     * @param fileUri Optional URI of the file to show issues for (from context menu)
     */
    public async showIssuesInFile(fileUri?: vscode.Uri): Promise<void> {
        // Determine which file to show issues for
        let filePath: string;
        if (fileUri) {
            filePath = fileUri.fsPath;
        } else {
            const editor = vscode.window.activeTextEditor;
            if (!editor) {
                vscode.window.showInformationMessage("No active editor");
                return;
            }
            filePath = editor.document.uri.fsPath;
        }
 
        // Filter highlights for this file
        const fileHighlights = this.allHighlightsCache.filter(
            (h) => h.filePath === filePath
        );
 
        if (fileHighlights.length === 0) {
            vscode.window.showInformationMessage(
                `No DataFlint issues in ${path.basename(filePath)}`
            );
            return;
        }
 
        // Group by severity
        const hotspots = fileHighlights.filter((h) => h.isHotspot);
        const alerts = fileHighlights.filter(
            (h) => !h.isHotspot && (h.alertCount ?? 0) > 0
        );
        const findings = fileHighlights.filter(
            (h) => !h.isHotspot && (h.alertCount ?? 0) === 0
        );
 
        // Build Quick Pick items
        interface IssueQuickPickItem extends vscode.QuickPickItem {
            highlight?: HighlightCodeLineData;
        }
 
        const items: IssueQuickPickItem[] = [];
 
        // Add hotspots
        if (hotspots.length > 0) {
            items.push({
                label: `🔥 Hotspots (${hotspots.length})`,
                kind: vscode.QuickPickItemKind.Separator,
            });
            for (const h of hotspots.sort((a, b) => a.codeLine - b.codeLine)) {
                items.push({
                    label: `$(flame) Line ${h.codeLine}`,
                    description:
                        h.text?.substring(0, 60) || "Performance hotspot",
                    detail: h.alerts?.join(", ") || undefined,
                    highlight: h,
                });
            }
        }
 
        // Add alerts
        if (alerts.length > 0) {
            items.push({
                label: `⚠️ Alerts (${alerts.length})`,
                kind: vscode.QuickPickItemKind.Separator,
            });
            for (const h of alerts.sort((a, b) => a.codeLine - b.codeLine)) {
                items.push({
                    label: `$(warning) Line ${h.codeLine}`,
                    description: h.text?.substring(0, 60) || "Alert",
                    detail: h.alerts?.join(", ") || undefined,
                    highlight: h,
                });
            }
        }
 
        // Add findings
        if (findings.length > 0) {
            items.push({
                label: `📊 Findings (${findings.length})`,
                kind: vscode.QuickPickItemKind.Separator,
            });
            for (const h of findings.sort((a, b) => a.codeLine - b.codeLine)) {
                items.push({
                    label: `$(lightbulb) Line ${h.codeLine}`,
                    description: h.text?.substring(0, 60) || "Finding",
                    highlight: h,
                });
            }
        }
 
        const selected = await vscode.window.showQuickPick(items, {
            title: `${fileHighlights.length} Issues in ${path.basename(filePath)}`,
            placeHolder: "Select an issue to jump to",
        });
 
        if (selected && selected.highlight) {
            await this.navigateToHighlight(selected.highlight);
        }
    }
 
    /**
     * Navigate to a specific highlight in the editor
     */
    private async navigateToHighlight(
        highlight: HighlightCodeLineData
    ): Promise<void> {
        const uri = vscode.Uri.file(highlight.filePath);
        const doc = await vscode.workspace.openTextDocument(uri);
        const editor = await vscode.window.showTextDocument(doc);
 
        // Calculate the actual line (0-indexed for VS Code)
        const lineIndex = Math.max(0, highlight.codeLine - 1);
 
        // Create position and selection
        const position = new vscode.Position(lineIndex, 0);
        editor.selection = new vscode.Selection(position, position);
 
        // Reveal the line in the center of the editor
        editor.revealRange(
            new vscode.Range(position, position),
            vscode.TextEditorRevealType.InCenter
        );
    }
 
    /**
     * Get all current highlights (for external access)
     */
    public getCurrentHighlights(): HighlightCodeLineData[] {
        return [...this.currentHighlightData];
    }
 
    /**
     * Get all cached highlights (for external access, includes filtered out items)
     */
    public getAllHighlights(): HighlightCodeLineData[] {
        return [...this.allHighlightsCache];
    }
 
    /**
     * Reveal all files with highlights in the Explorer tree.
     * This expands all parent folders to make highlighted files visible.
     */
    public async revealAllHighlights(): Promise<void> {
        const logger = Logger.getInstance();
        const allHighlights = this.getAllHighlights();
 
        if (allHighlights.length === 0) {
            vscode.window.showInformationMessage(
                "No DataFlint highlights to reveal"
            );
            return;
        }
 
        // Get unique file paths
        const uniqueFiles = [...new Set(allHighlights.map((h) => h.filePath))];
 
        logger.debug(
            `Revealing ${uniqueFiles.length} files with DataFlint highlights`
        );
 
        // Reveal files concurrently for better performance
        await Promise.all(
            uniqueFiles.map((filePath) =>
                vscode.commands.executeCommand(
                    "revealInExplorer",
                    vscode.Uri.file(filePath)
                )
            )
        );
 
        vscode.window.showInformationMessage(
            `Revealed ${uniqueFiles.length} file${uniqueFiles.length === 1 ? "" : "s"} with DataFlint highlights`
        );
    }
 
    /**
     * Dispose all highlights (cleanup)
     */
    public dispose(): void {
        const logger = Logger.getInstance();
 
        // Dispose file watchers
        this.fileWatchers.forEach((watcher) => watcher.dispose());
        this.fileWatchers.clear();
 
        // Clear refresh timer
        if (this.refreshTimer) {
            clearTimeout(this.refreshTimer);
        }
 
        // Dispose status bar
        this.statusBarItem?.dispose();
        this.statusBarItem = null;
 
        // Dispose decoration manager
        this.decorationManager.dispose();
 
        // Dispose file decoration provider
        this.fileDecorationProvider.dispose();
        this.fileDecorationDisposable.dispose();
        this.diagnosticProvider.dispose();
 
        // Dispose event listeners
        this.codeLensDisposable?.dispose();
        this.fileWatcherDisposable?.dispose();
        this.editorChangeDisposable?.dispose();
 
        this.currentHighlightData = [];
        this.allHighlightsCache = [];
        this.activeQueryFilter = null;
        this.clearedHighlights = null;
        logger.info("DataFlintHighlights disposed");
    }
}