All files / src/views snapshotManager.ts

41.44% Statements 378/912
58.2% Branches 39/67
70.37% Functions 19/27
41.44% Lines 378/912

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 9121x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                       13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 1x 13x 13x                             1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                         1x 1x 1x 1x 1x 1x 1x 1x             1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x             1x 1x           1x             13x 13x 13x 12x 12x 12x 12x 12x     12x     13x 12x 12x 13x             1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x             1x 1x 1x 1x                   1x                         1x 1x         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       2x 2x 1x 1x 1x 1x 1x 2x       1x 1x 1x 2x         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x     2x                                                                                                                                 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x               5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 10x 10x 10x 10x 10x 10x 10x 10x     10x 5x 5x       3x 3x 3x 3x 6x 6x 6x 6x 6x 6x 6x 6x 3x 3x 3x             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             3x 3x 3x 6x 6x 6x 6x 9x 1x 9x 1x 1x 9x 6x 3x 3x 3x     2x 2x 2x                                                                                                                                                                                                                                                                                                                                                                                                                     1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x                                                                                                               1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x               1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
// snapshotManager.ts
import * as vscode from "vscode";
import * as path from "path";
import { SupabaseClient } from "@supabase/supabase-js";
import { createTwoFilesPatch } from "diff"; // ensure `diff` is installed
import { getCurrentUserId } from "../services/auth-service";
import { getSupabase } from "../auth/supabaseClient";
 
type FileMap = Record<string, string>;
 
export class SnapshotManager {
  private supabase: SupabaseClient;
  private idleTimer: NodeJS.Timeout | null = null;
  private IDLE_DELAY = 20_000; // 20s idle window for demo

  // Thresholds for creating new snapshots
  private LINES_THRESHOLD = 50;  // Minimum lines changed
  private FILES_THRESHOLD = 5;   // Minimum files changed

  /** The original/baseline snapshot of the whole workspace (first full capture) */
  private baselineSnapshot: FileMap | null = null;

  /** Session baseline snapshot for Live Share sessions (host only) */
  private sessionBaselineSnapshot: FileMap | null = null;

  /** Flag to track if automatic snapshotting is paused (during Live Share) */
  private isAutomaticTrackingPaused: boolean = false;

  /** Workspace root path for relative path conversion */
  private workspaceRoot: string;

  /** Broadcast cooldown tracking */
  private lastBroadcastTime: number = 0;
  private BROADCAST_COOLDOWN = 60_000; // 60 seconds cooldown

  /** Track if user has been notified about missing initial snapshot */
  private hasShownInitialSnapshotWarning: boolean = false;

  /** Track if we're currently taking an initial snapshot */
  private isTakingInitialSnapshot: boolean = false;

  // ==========================================
  // GLOBAL RATE LIMITING (AI API Cost Protection)
  // ==========================================
  /**
   * Global rate limit for ALL snapshot triggers (passive + active)
   * Per user: 16 AI snapshots per hour (independent of team)
   */
  private readonly MAX_SNAPSHOTS_PER_HOUR = 16;
  private readonly RATE_LIMIT_WINDOW_MS = 60 * 60 * 1000; // 1 hour

  /**
   * Track snapshot timestamps per user
   * Key: userId, Value: array of timestamps (sorted, oldest first)
   */
  private snapshotHistory: Map<string, number[]> = new Map();

  /** Track if user has been shown rate limit warning for current hour */
  private hasShownRateLimitWarning: Map<string, boolean> = new Map();

  constructor(private context: vscode.ExtensionContext) {
    this.supabase = getSupabase();
 
    // Initialize workspace root
    const workspaceFolders = vscode.workspace.workspaceFolders;
    this.workspaceRoot = workspaceFolders?.[0]?.uri.fsPath || '';
 
    // Load persisted rate limit history from storage
    this.loadRateLimitHistory();
 
    vscode.workspace.onDidChangeTextDocument(() => this.onWorkspaceActivity());
    vscode.workspace.onDidCreateFiles(() => this.onWorkspaceActivity());
    vscode.workspace.onDidDeleteFiles(() => this.onWorkspaceActivity());
    vscode.workspace.onDidRenameFiles(() => this.onWorkspaceActivity());
 
    // Monitor when files are opened to check for initial snapshot
    vscode.workspace.onDidOpenTextDocument((document) => this.checkInitialSnapshotOnFileOpen(document));
 
    // Check if there are already open documents when extension activates
    // Use a small delay to ensure extension context is fully initialized
    setTimeout(() => {
      this.checkAlreadyOpenDocuments();
    }, 1000);
  }

  // ==========================================
  // GLOBAL RATE LIMITING METHODS
  // ==========================================

  /**
   * Checks if the user has exceeded the hourly snapshot limit.
   * Returns an object with:
   * - allowed: boolean - whether snapshot is allowed
   * - remaining: number - snapshots remaining in current window
   * - resetTime: Date - when the quota resets
   * - message: string - user-friendly message
   */
  private checkRateLimit(userId: string): {
    allowed: boolean;
    remaining: number;
    resetTime: Date | null;
    message: string;
  } {
    const now = Date.now();
 
    // Get or initialize snapshot history for this user
    let history = this.snapshotHistory.get(userId) || [];
 
    // Remove snapshots older than 1 hour (sliding window)
    history = history.filter(timestamp => now - timestamp < this.RATE_LIMIT_WINDOW_MS);
 
    // Update the history
    this.snapshotHistory.set(userId, history);
 
    const snapshotsInWindow = history.length;
    const remaining = this.MAX_SNAPSHOTS_PER_HOUR - snapshotsInWindow;
 
    if (snapshotsInWindow >= this.MAX_SNAPSHOTS_PER_HOUR) {
      // Find the oldest snapshot to calculate reset time
      const oldestSnapshot = history[0];
      const resetTime = new Date(oldestSnapshot + this.RATE_LIMIT_WINDOW_MS);
      const minutesUntilReset = Math.ceil((resetTime.getTime() - now) / 60000);

      return {
        allowed: false,
        remaining: 0,
        resetTime: resetTime,
        message: `⏱️ AI snapshot limit reached (${this.MAX_SNAPSHOTS_PER_HOUR}/hour). Quota resets in ${minutesUntilReset} minute(s). This helps manage API costs.`
      };
    }
 
    return {
      allowed: true,
      remaining: remaining,
      resetTime: history.length > 0 ? new Date(history[0] + this.RATE_LIMIT_WINDOW_MS) : null,
      message: `${remaining} AI snapshot(s) remaining this hour`
    };
  }

  /**
   * Records a snapshot in the rate limit history.
   * Call this AFTER successfully creating a snapshot.
   */
  private recordSnapshot(userId: string): void {
    const now = Date.now();
    const history = this.snapshotHistory.get(userId) || [];
    history.push(now);
    this.snapshotHistory.set(userId, history);
 
    // Reset the warning flag so user can be warned again next hour
    this.hasShownRateLimitWarning.delete(userId);
 
    // Persist to storage to prevent restart bypass
    this.saveRateLimitHistory();
  }

  /**
   * Shows a one-time warning per hour when user is getting close to limit.
   * Call this when user has 2 or fewer snapshots remaining.
   */
  private showRateLimitWarningIfNeeded(userId: string, remaining: number): void {
    // Only show warning once per hour, and only when 2 or fewer remain
    if (remaining <= 2 && !this.hasShownRateLimitWarning.get(userId)) {
      vscode.window.showWarningMessage(
        `⚠️ AI Snapshot Budget: Only ${remaining} snapshot(s) remaining this hour. Please use wisely to manage API costs.`
      );
      this.hasShownRateLimitWarning.set(userId, true);
    }
  }

  /**
   * Loads rate limit history from persistent storage (globalState).
   * Called on extension startup to prevent rate limit bypass via restart.
   */
  private loadRateLimitHistory(): void {
    try {
      const stored = this.context.globalState.get<Record<string, number[]>>('snapshotRateLimitHistory');
      if (stored) {
        const now = Date.now();
        // Convert stored object to Map and filter out expired snapshots
        for (const [userId, timestamps] of Object.entries(stored)) {
          const validTimestamps = timestamps.filter(ts => now - ts < this.RATE_LIMIT_WINDOW_MS);
          if (validTimestamps.length > 0) {
            this.snapshotHistory.set(userId, validTimestamps);
          }
        }
        console.log('[SnapshotManager] Rate limit history loaded from storage');
      }
    } catch (error) {
      console.error('[SnapshotManager] Failed to load rate limit history:', error);
    }
  }

  /**
   * Saves rate limit history to persistent storage (globalState).
   * Called after each snapshot to prevent rate limit bypass via restart.
   */
  private saveRateLimitHistory(): void {
    try {
      // Convert Map to plain object for storage
      const toStore: Record<string, number[]> = {};
      for (const [userId, timestamps] of this.snapshotHistory.entries()) {
        if (timestamps.length > 0) {
          toStore[userId] = timestamps;
        }
      }
      this.context.globalState.update('snapshotRateLimitHistory', toStore);
    } catch (error) {
      console.error('[SnapshotManager] Failed to save rate limit history:', error);
    }
  }

  /**
   * Checks already-open documents when extension activates
   * This handles the case where user has files open before initial snapshot is taken
   */
  private async checkAlreadyOpenDocuments() {
    // Check if we have any text documents already open
    const openDocuments = vscode.workspace.textDocuments;
 
    if (openDocuments.length > 0) {
      // Check the active (visible) document first if it exists
      const activeDocument = vscode.window.activeTextEditor?.document;
      if (activeDocument) {
        await this.checkInitialSnapshotOnFileOpen(activeDocument);
      } else if (openDocuments.length > 0) {
        // If no active document, check the first open document
        await this.checkInitialSnapshotOnFileOpen(openDocuments[0]);
      }
    }
  }

  // ——————————————————————
  // Public APIs you already call
  // ——————————————————————

  /** Check if baseline snapshot exists */
  public hasBaselineSnapshot(): boolean {
    return this.baselineSnapshot !== null;
  }

  /** Initial full snapshot (called when team is selected) */
  public async takeSnapshot(userId: string, projectName: string, teamId?: string) {
    // Require teamId for snapshot
    if (!teamId) {
      console.warn('[SnapshotManager] No team selected - skipping snapshot');
      vscode.window.showWarningMessage('Please select a team before taking snapshots');
      return;
    }
 
    // Mark that we're taking initial snapshot
    this.isTakingInitialSnapshot = true;
 
    vscode.window.showInformationMessage('📸 Taking initial workspace snapshot...');
 
    const snapshot = await this.captureWholeWorkspace();
 
    // Save baseline in memory
    this.baselineSnapshot = snapshot;
 
    // Reset warning flag since initial snapshot is now taken
    this.hasShownInitialSnapshotWarning = false;
 
    // Write to DB: snapshot (all files), clear changes
    await this.insertNewSnapshot(userId, projectName, teamId, snapshot, {});
 
    const fileCount = Object.keys(snapshot).length;
    vscode.window.showInformationMessage(`✅ Initial snapshot complete: ${fileCount} files captured`);
    console.log("Full workspace snapshot saved.");
 
    // Mark that we're done taking initial snapshot
    this.isTakingInitialSnapshot = false;
  }

  /** Idle-based incremental snapshot: recompute ALL changes vs baseline and check thresholds */
  public async takeIncrementalSnapshot(userId: string, teamId?: string) {
    // Require teamId for snapshot
    if (!teamId) {
      console.log('[SnapshotManager] No team selected - skipping incremental snapshot');
      return;
    }
 
    // Initial snapshots should ONLY be created when the user clicks "Switch Team".
    if (!this.baselineSnapshot) {
      console.log('[SnapshotManager] No baseline snapshot exists - automatic snapshots will not run until user selects a team via Switch Team');
      return;
    }
 
    // ====== GLOBAL RATE LIMIT CHECK (per-user) ======
    const rateLimit = this.checkRateLimit(userId);
    if (!rateLimit.allowed) {
      console.log(`[SnapshotManager] Rate limit exceeded: ${rateLimit.message}`);
      vscode.window.showWarningMessage(rateLimit.message);
      return;
    }
 
    // Show warning if getting close to limit
    this.showRateLimitWarningIfNeeded(userId, rateLimit.remaining);
    // =================================================
 
    const projectName = this.getProjectName();
    const current = await this.captureWholeWorkspace();
 
    // Build merged diffs vs the ORIGINAL baseline, per file
    const mergedChanges = this.computeUnifiedDiffs(this.baselineSnapshot, current);
 
    // Check if changes meet threshold
    const filesChanged = Object.keys(mergedChanges).length;
    const linesChanged = this.countTotalLines(mergedChanges);
 
    console.log(`[SnapshotManager] Changes detected: ${filesChanged} files, ${linesChanged} lines`);
 
    // Only create snapshot if threshold is met
    if (linesChanged >= this.LINES_THRESHOLD || filesChanged >= this.FILES_THRESHOLD) {
      vscode.window.showInformationMessage(
        `📸 Capturing snapshot: ${filesChanged} files, ${linesChanged} lines changed (${rateLimit.remaining - 1} AI snapshots left this hour)`
      );
 
      // Create NEW row with ONLY changes (not full workspace)
      // Pass empty object {} for snapshot to save space
      await this.insertNewSnapshot(userId, projectName, teamId, {}, mergedChanges);
 
      // Record snapshot in rate limit history (per-user)
      this.recordSnapshot(userId);
 
      vscode.window.showInformationMessage(
        `✅ Snapshot sent to AI for analysis`
      );
 
      // Update baseline to current state
      this.baselineSnapshot = current;
 
      console.log("Incremental snapshot saved and sent to AI.");
    } else {
      console.log(`[SnapshotManager] Threshold not met (need ${this.LINES_THRESHOLD} lines or ${this.FILES_THRESHOLD} files). Skipping snapshot.`);
    }
  }

  // Initial snapshot notification
  /**
   * Checks if initial snapshot exists when user opens a file.
   * Shows a one-time notification if no baseline snapshot exists.
   */
  private async checkInitialSnapshotOnFileOpen(document: vscode.TextDocument) {
    // Only check for workspace files (not settings, output panels, etc.)
    if (document.uri.scheme !== 'file') {
      return;
    }

    // Skip if already shown warning
    if (this.hasShownInitialSnapshotWarning) {
      return;
    }

    // Skip if we're currently taking an initial snapshot
    if (this.isTakingInitialSnapshot) {
      return;
    }

    // Skip if baseline snapshot exists
    if (this.baselineSnapshot) {
      return;
    }

    // Skip if no workspace is open
    if (!vscode.workspace.workspaceFolders?.length) {
      return;
    }

    // Check if file is within the workspace
    const workspaceFolder = vscode.workspace.getWorkspaceFolder(document.uri);
    if (!workspaceFolder) {
      return;
    }

    // Check if user is signed in
    const userId = await getCurrentUserId();
    if (!userId) {
      // User not signed in yet, don't show notification
      return;
    }

    // Mark as shown to prevent repeated notifications
    this.hasShownInitialSnapshotWarning = true;

    // Show notification with action button
    vscode.window.showInformationMessage(
      'No initial snapshot detected. Please select a team in the Team panel to track your changes and share updates with your team.',
      'Open Team Panel'
    ).then(selection => {
      if (selection === 'Open Team Panel') {
        // Open the Team Activity panel
        vscode.commands.executeCommand('workbench.view.extension.collabAgent');
      }
    });
  }

  // ——————————————————————
  // Idle handling
  // ——————————————————————
  private onWorkspaceActivity() {
    // Don't start idle timer if automatic tracking is paused
    if (this.isAutomaticTrackingPaused) {
      console.log('[SnapshotManager] Automatic tracking paused - ignoring workspace activity');
      return;
    }
 
    if (this.idleTimer) clearTimeout(this.idleTimer);
    this.idleTimer = setTimeout(async () => {
      const userId = await this.requireUser();
      // Use the same key as AgentPanel (collabAgent.currentTeam)
      const teamId = this.context.globalState.get<string>('collabAgent.currentTeam');
      console.log('[SnapshotManager] Idle timer fired - teamId:', teamId);
      if (userId) await this.takeIncrementalSnapshot(userId, teamId);
    }, this.IDLE_DELAY);
  }

  // ——————————————————————
  // Core helpers
  // ——————————————————————

  /** Capture ALL text files in the workspace (not just open editors). */
  private async captureWholeWorkspace(): Promise<FileMap> {
    const files: FileMap = {};
 
    if (!vscode.workspace.workspaceFolders?.length) return files;
 
    // Skip common noise
    const exclude =
      "{**/.git/**,**/node_modules/**,**/.vscode/**,**/dist/**,**/out/**," +
      "**/*.png,**/*.jpg,**/*.jpeg,**/*.gif,**/*.svg,**/*.pdf,**/*.ico," +
      "**/*.zip,**/*.gz,**/*.tar,**/*.lock,**/*.min.js}";
 
    // Capture up to ~10k files—adjust if you need more/less
    const uris = await vscode.workspace.findFiles("**/*", exclude, 10000);
 
    // Read each as text; errors are ignored (binarys etc)
    for (const uri of uris) {
      try {
        const doc = await vscode.workspace.openTextDocument(uri);
        // Use RELATIVE paths for portability across machines
        const relativePath = this.workspaceRoot
          ? path.relative(this.workspaceRoot, uri.fsPath)
          : uri.fsPath;
        files[relativePath] = doc.getText();
      } catch {
        // Ignore unreadable files
      }
    }
    return files;
  }

  /** Compute a map: filePath -> unified diff string, comparing current against baseline. */
  private computeUnifiedDiffs(baseline: FileMap, current: FileMap): Record<string, string> {
    const changed: Record<string, string> = {};
    const seen = new Set<string>([...Object.keys(baseline), ...Object.keys(current)]);
 
    for (const file of seen) {
      const oldText = baseline[file] ?? "";
      const newText = current[file] ?? "";
      if (oldText === newText) continue;
 
      // Unified diff (shows + and - clearly, and handles add/delete/edit)
      const patch = createTwoFilesPatch(file, file, oldText, newText, "baseline", "current");
      changed[file] = patch;
    }
 
    return changed;
  }

  /**
   * Insert a NEW snapshot row (not upsert) so edge function triggers on each insert
   * This allows AI to summarize each work session separately
   */
  private async insertNewSnapshot(
    userId: string,
    projectName: string,
    teamId: string,
    snapshot: FileMap,
    changes: Record<string, string>
  ) {
    const payload = {
      user_id: userId,
      team_id: teamId, // Fixed: using team_id instead of project_name
      project_name: projectName,
      snapshot: snapshot,
      changes: changes,
      updated_at: new Date().toISOString(),
    };
 
    console.log("[DB INSERT] Creating new snapshot row...");
 
    const { data, error } = await this.supabase
      .from("file_snapshots")
      .insert(payload)
      .select();
 
    if (error) {
      console.error("Failed to insert snapshot:", error);
      vscode.window.showErrorMessage(`Failed to save snapshot: ${error.message}`);
    } else {
      console.log(`✅ Snapshot successfully inserted for project: ${projectName}`);
      if (data && data.length > 0) {
        console.log(`   Snapshot ID: ${data[0].id}`);
      }
    }
  }

  /**
   * Count total lines changed across all diffs
   * Counts lines starting with + or - (but not +++ or ---)
   */
  private countTotalLines(diffs: Record<string, string>): number {
    let total = 0;
 
    for (const diff of Object.values(diffs)) {
      // Count lines starting with + or - (actual changes)
      // Exclude lines starting with +++ or --- (file headers)
      const lines = diff.split('\n');
      for (const line of lines) {
        if (line.startsWith('+') && !line.startsWith('+++')) {
          total++;
        } else if (line.startsWith('-') && !line.startsWith('---')) {
          total++;
        }
      }
    }
 
    return total;
  }

  private getProjectName(): string {
    const w = vscode.workspace.workspaceFolders?.[0];
    return w?.name ?? "untitled-workspace";
  }

  /**
   * Publishes a timeline snapshot:
   * Creates a new snapshot marking a milestone/publish event
   */
  public async publishSnapshot(userId: string, projectName: string, teamId?: string) {
    // Require teamId for snapshot
    if (!teamId) {
      console.warn('[SnapshotManager] No team selected - skipping publish');
      vscode.window.showWarningMessage('Please select a team before publishing snapshots');
      return;
    }

    vscode.window.showInformationMessage('📤 Publishing snapshot to timeline...');

    const newSnapshot = await this.captureWholeWorkspace();
    const diff = this.computeUnifiedDiffs(this.baselineSnapshot || {}, newSnapshot);

    // Create a new snapshot row with ONLY changes (not full workspace)
    await this.insertNewSnapshot(userId, projectName, teamId, {}, diff);

    vscode.window.showInformationMessage('✅ Snapshot published successfully');

    // Update baseline to current state
    this.baselineSnapshot = newSnapshot;
  }


  /**
   * Manual user-triggered snapshot
   * Creates a new snapshot immediately regardless of thresholds
   */
  public async userTriggeredSnapshot(userId: string, projectName: string, teamId?: string) {
    // Require teamId for snapshot
    if (!teamId) {
      console.warn('[SnapshotManager] No team selected - skipping manual snapshot');
      vscode.window.showWarningMessage('Please select a team before taking snapshots');
      return;
    }

    vscode.window.showInformationMessage('📸 Capturing manual snapshot...');

    const newSnapshot = await this.captureWholeWorkspace();
    const diff = this.computeUnifiedDiffs(this.baselineSnapshot || {}, newSnapshot);

    const filesChanged = Object.keys(diff).length;
    const linesChanged = this.countTotalLines(diff);

    // Create new snapshot row with ONLY changes (not full workspace)
    await this.insertNewSnapshot(userId, projectName, teamId, {}, diff);

    vscode.window.showInformationMessage(
      `✅ Manual snapshot complete: ${filesChanged} files, ${linesChanged} lines`
    );

    // Update baseline to current state
    this.baselineSnapshot = newSnapshot;
  }

  /**
   * Broadcast snapshot - Manual override that bypasses automatic snapshot constraints
   * Checks:
   * 1. Initial snapshot exists
   * 2. At least 2 lines changed
   * 3. 60-second cooldown occured
   * 4. Global rate limit not exceeded (10/hour across all triggers)
   * Returns success/error object
   */
  public async broadcastSnapshot(userId: string, projectName: string, teamId?: string): Promise<{success: boolean, message: string}> {
    // Require teamId for snapshot
    if (!teamId) {
      console.warn('[SnapshotManager] No team selected - skipping broadcast');
      return {
        success: false,
        message: 'Please select a team before broadcasting snapshots'
      };
    }

    // Check 1: Initial snapshot must exist
    if (!this.baselineSnapshot) {
      console.log('[SnapshotManager] No baseline snapshot exists - cannot broadcast');
      return {
        success: false,
        message: 'Please trigger initial snapshot first by switching to a team'
      };
    }

    // Check 2: Global rate limit (per-user, applies to both passive AND active triggers)
    const rateLimit = this.checkRateLimit(userId);
    if (!rateLimit.allowed) {
      console.log(`[SnapshotManager] Rate limit exceeded for broadcast: ${rateLimit.message}`);
      return {
        success: false,
        message: rateLimit.message
      };
    }

    // Show warning if getting close to limit
    this.showRateLimitWarningIfNeeded(userId, rateLimit.remaining);

    // Check 3: Cooldown period (broadcast-specific, prevents spam clicking)
    const now = Date.now();
    const timeSinceLastBroadcast = now - this.lastBroadcastTime;
    if (timeSinceLastBroadcast < this.BROADCAST_COOLDOWN) {
      const remainingSeconds = Math.ceil((this.BROADCAST_COOLDOWN - timeSinceLastBroadcast) / 1000);
      console.log(`[SnapshotManager] Broadcast cooldown active - ${remainingSeconds}s remaining`);
      return {
        success: false,
        message: `Please wait ${remainingSeconds} seconds before broadcasting again`
      };
    }

    // Capture current state and compute changes
    const newSnapshot = await this.captureWholeWorkspace();
    const diff = this.computeUnifiedDiffs(this.baselineSnapshot, newSnapshot);

    const filesChanged = Object.keys(diff).length;
    const linesChanged = this.countTotalLines(diff);

    console.log(`[SnapshotManager] Broadcast check: ${filesChanged} files, ${linesChanged} lines changed`);

    // Check 4: At least 2 lines changed
    if (linesChanged < 2) {
      console.log('[SnapshotManager] Insufficient changes for broadcast (need at least 2 lines)');
      return {
        success: false,
        message: `Only ${linesChanged} line(s) changed. Need at least 2 lines to broadcast`
      };
    }

    // All checks passed - create broadcast snapshot
    vscode.window.showInformationMessage(
      `📡 Broadcasting snapshot: ${filesChanged} files, ${linesChanged} lines changed (${rateLimit.remaining - 1} AI snapshots left this hour)`
    );

    // Create new snapshot row with broadcast marker in file_path
    const payload = {
      user_id: userId,
      team_id: teamId,
      project_name: projectName,
      snapshot: {},
      changes: diff,
      file_path: '[BROADCAST]', // Special marker for broadcast snapshots
      updated_at: new Date().toISOString(),
    };

    const { data, error } = await this.supabase
      .from("file_snapshots")
      .insert(payload)
      .select();

    if (error) {
      console.error('[SnapshotManager] Failed to broadcast snapshot:', error);
      return {
        success: false,
        message: `Failed to broadcast: ${error.message}`
      };
    }

    // Update cooldown timer
    this.lastBroadcastTime = now;

    // Record snapshot in rate limit history (per-user)
    this.recordSnapshot(userId);

    // Update baseline to current state
    this.baselineSnapshot = newSnapshot;

    console.log('[SnapshotManager] Broadcast snapshot created successfully');

    vscode.window.showInformationMessage(
      `✅ Broadcast successful: ${filesChanged} files, ${linesChanged} lines`
    );

    return {
      success: true,
      message: `Broadcast successful: ${filesChanged} files, ${linesChanged} lines changed`
    };
  }

  private async requireUser(): Promise<string> {
    const userId = await getCurrentUserId();
    if (!userId) {
      console.warn("User not signed in — skipping snapshot");
    }
    return userId ?? "";
  }

  // ——————————————————————
  // Live Share Integration Methods
  // ——————————————————————

  /**
   * Saves any pending local changes and pauses automatic snapshot tracking.
   * Called when user joins or starts a Live Share session.
   * CRITICAL: This ALWAYS saves pending changes, regardless of thresholds,
   * to prevent data loss when starting a Live Share session.
   *
   * IMPORTANT: This should be called AFTER createSessionBaseline() for hosts,
   * so the session baseline includes the pending changes.
   */
  public async pauseAutomaticTracking(userId: string, teamId?: string) {
    console.log('[SnapshotManager] Pausing automatic tracking for Live Share session');
 
    if (!teamId) {
      console.warn('[SnapshotManager] No team selected - skipping final snapshot');
    } else {
      // IMPORTANT: Force save ANY pending changes, even if below thresholds
      // This prevents data loss when starting a Live Share session
      await this.forceSavePendingChanges(userId, teamId);
    }
 
    // Pause automatic tracking
    this.isAutomaticTrackingPaused = true;
 
    // Clear any pending idle timer
    if (this.idleTimer) {
      clearTimeout(this.idleTimer);
      this.idleTimer = null;
    }
 
    console.log('[SnapshotManager] Automatic tracking paused');
  }

  /**
   * Forces a snapshot of ANY pending changes, regardless of thresholds.
   * Used when starting a Live Share session to prevent data loss.
   * This ensures even small uncommitted changes are preserved.
   */
  private async forceSavePendingChanges(userId: string, teamId: string) {
    console.log('[SnapshotManager] Force-saving pending changes (ignoring thresholds)');

    // Initial snapshots should ONLY be created when the user clicks "Switch Team".
    if (!this.baselineSnapshot) {
      console.log('[SnapshotManager] No baseline snapshot exists - cannot save pending changes. User must select team via Switch Team first.');
      vscode.window.showWarningMessage('Please select a team via Switch Team before starting a Live Share session');
      return;
    }

    const projectName = this.getProjectName();
    const current = await this.captureWholeWorkspace();

    // Build diffs vs the baseline
    const changes = this.computeUnifiedDiffs(this.baselineSnapshot, current);

    const filesChanged = Object.keys(changes).length;
    const linesChanged = this.countTotalLines(changes);

    console.log(`[SnapshotManager] Pending changes: ${filesChanged} files, ${linesChanged} lines`);

    // Save changes REGARDLESS of threshold (this is the key fix for Bug 2)
    if (filesChanged > 0 || linesChanged > 0) {
      vscode.window.showInformationMessage(
        `📸 Saving pending work before session: ${filesChanged} files, ${linesChanged} lines`
      );

      // Create NEW row with ONLY changes (not full workspace)
      await this.insertNewSnapshot(userId, projectName, teamId, {}, changes);

      // Update baseline to current state
      this.baselineSnapshot = current;

      console.log('[SnapshotManager] Pending changes saved successfully');
    } else {
      console.log('[SnapshotManager] No pending changes to save');
    }
  }

  /**
   * Creates a session baseline snapshot for the host.
   * This snapshot will be used to calculate the diff when the session ends.
   * Called only when user is the host (starts a session).
   * Returns the snapshot ID for linking to the session event.
   *
   * CRITICAL: This captures the CURRENT workspace state, including any uncommitted changes.
   * This must be called BEFORE pauseAutomaticTracking() so it includes pending work.
   */
  public async createSessionBaseline(userId: string, teamId: string, sessionId: string): Promise<string | null> {
    console.log('[SnapshotManager] Creating session baseline snapshot (including pending changes)');
 
    // Capture current workspace state as session baseline (includes ALL uncommitted work)
    this.sessionBaselineSnapshot = await this.captureWholeWorkspace();
 
    const fileCount = Object.keys(this.sessionBaselineSnapshot).length;
    console.log(`[SnapshotManager] Session baseline created: ${fileCount} files`);
 
    // Save the session baseline to database so "View Initial Snapshot" button works
    // Use a special file_path format to identify this as a session baseline
    const projectName = this.getProjectName();
    const baselinePayload = {
      user_id: userId,
      team_id: teamId,
      project_name: projectName,
      snapshot: this.sessionBaselineSnapshot,  // Full snapshot INCLUDING pending changes
      changes: {},  // No changes - this is the baseline
      file_path: `Live Share Session ${sessionId} (baseline)`,
      updated_at: new Date().toISOString(),
    };
 
    console.log('[SnapshotManager] Saving session baseline to database...');
 
    const { data, error } = await this.supabase
      .from("file_snapshots")
      .insert(baselinePayload)
      .select();
 
    if (error) {
      console.error('[SnapshotManager] Failed to save session baseline:', error);
      return null;
    }
 
    const snapshotId = data && data.length > 0 ? data[0].id : null;
    console.log(`[SnapshotManager] Session baseline saved with ID: ${snapshotId}`);
 
    return snapshotId;
  }

  /**
   * Resumes automatic snapshot tracking after a Live Share session ends.
   * Takes a new initial snapshot to set a fresh baseline for local changes.
   * Called when session ends (both host and guest).
   */
  public async resumeAutomaticTracking(userId: string, projectName: string, teamId?: string) {
    console.log('[SnapshotManager] Resuming automatic tracking after Live Share session');
 
    if (!teamId) {
      console.warn('[SnapshotManager] No team selected - skipping snapshot');
    } else {
      // Take a new initial snapshot to set a fresh baseline for local changes
      vscode.window.showInformationMessage('📸 Taking snapshot after session...');
      await this.takeSnapshot(userId, projectName, teamId);
      // Note: takeSnapshot already resets hasShownInitialSnapshotWarning
    }
 
    // Resume automatic tracking
    this.isAutomaticTrackingPaused = false;
 
    console.log('[SnapshotManager] Automatic tracking resumed');
  }

  /**
   * Calculates and saves the session diff (host only).
   * Compares current state against the session baseline created at session start.
   * Returns the changes as a unified diff string.
   * Called only when the host ends the session.
   */
  public async captureSessionChanges(userId: string, teamId: string): Promise<string> {
    console.log('[SnapshotManager] Capturing session changes');
 
    if (!this.sessionBaselineSnapshot) {
      console.warn('[SnapshotManager] No session baseline found - cannot calculate session changes');
      return '';
    }
 
    // Capture current workspace state
    const currentSnapshot = await this.captureWholeWorkspace();
 
    // Calculate diff against session baseline
    const sessionDiff = this.computeUnifiedDiffs(this.sessionBaselineSnapshot, currentSnapshot);
 
    // Convert diff map to a single string
    let diffString = '';
    for (const [filePath, diff] of Object.entries(sessionDiff)) {
      diffString += `\n=== ${filePath} ===\n${diff}\n`;
    }
 
    const filesChanged = Object.keys(sessionDiff).length;
    const linesChanged = this.countTotalLines(sessionDiff);
 
    console.log(`[SnapshotManager] Session changes: ${filesChanged} files, ${linesChanged} lines`);
 
    // Clear the session baseline
    this.sessionBaselineSnapshot = null;
 
    return diffString;
  }
}