'use strict';

const fs = require('fs');
const path = require('path');
const { execFileSync } = require('child_process');
const crypto = require('crypto');

const HOME = process.env.HOME || process.env.USERPROFILE || '';
const VSCDB = path.join(
  HOME,
  'Library/Application Support/Cursor/User/globalStorage/state.vscdb'
);
const LOOP_DIR = path.join(HOME, '.cursor-loop');
const ACTIVE_VERTICAL = path.join(LOOP_DIR, 'active-vertical.json');

function normTitle(title) {
  const t = String(title || '').trim();
  return t || '(未命名标签)';
}

function readActiveVertical() {
  try {
    const raw = fs.readFileSync(ACTIVE_VERTICAL, 'utf8');
    const j = JSON.parse(raw);
    if (j && j.title) return j;
  } catch {}
  return null;
}

function writeActiveVertical(payload) {
  try {
    fs.mkdirSync(LOOP_DIR, { recursive: true });
    fs.writeFileSync(
      ACTIVE_VERTICAL,
      JSON.stringify({ ...payload, updatedAt: Date.now() }, null, 2)
    );
  } catch {}
}

function queryVscdb(sql) {
  if (!fs.existsSync(VSCDB)) return null;
  try {
    return execFileSync('sqlite3', [VSCDB, sql], { encoding: 'utf8', timeout: 3000 }).trim();
  } catch {
    return null;
  }
}

function loadComposerHeaders() {
  const raw = queryVscdb(
    "SELECT value FROM ItemTable WHERE key='composer.composerHeaders' LIMIT 1;"
  );
  if (!raw) return null;
  try {
    return JSON.parse(raw);
  } catch {
    return null;
  }
}

function pickComposer(headers, opts = {}) {
  const list = headers?.allComposers || [];
  const composerId =
    opts.composerId ||
    process.env.CURSOR_CONVERSATION_ID ||
    process.env.CURSOR_CHAT_ID ||
    process.env.COMPOSER_ID ||
    readActiveVertical()?.composerId;

  if (composerId) {
    const hit = list.find((c) => c.composerId === composerId);
    if (hit) return hit;
  }

  const wsHint = String(opts.workspace || '').replace(/\/+$/, '');
  const candidates = list.filter((c) => c.type === 'head' && !c.isArchived);
  if (wsHint) {
    const wsMatch = candidates.filter((c) => {
      const cfg = c.workspaceIdentifier?.configPath;
      const fp = cfg?.fsPath || cfg?.path || '';
      return fp && (wsHint.includes(fp) || fp.includes(wsHint));
    });
    if (wsMatch.length) {
      wsMatch.sort((a, b) => (b.lastUpdatedAt || 0) - (a.lastUpdatedAt || 0));
      return wsMatch[0];
    }
  }
  candidates.sort((a, b) => (b.lastUpdatedAt || 0) - (a.lastUpdatedAt || 0));
  return candidates[0] || null;
}

/** 解析当前 Cursor Agent 标签名（真源：args > threadLock > active-vertical > vscdb） */
function resolveCursorTabTitle(opts = {}) {
  const fromArgs = opts.cursorTitle || opts.title;
  if (fromArgs && normTitle(fromArgs) !== '(未命名标签)') {
    return { title: normTitle(fromArgs), source: 'args', composerId: opts.composerId || null };
  }

  const active = readActiveVertical();
  if (active?.title && normTitle(active.title) !== '(未命名标签)') {
    const age = Date.now() - (active.updatedAt || 0);
    if (age < 30 * 60 * 1000) {
      return {
        title: normTitle(active.title),
        source: 'active-vertical',
        composerId: active.composerId || null,
      };
    }
  }

  const envTitle = process.env.CURSOR_CHAT_TITLE || process.env.PCHAT_CURSOR_TITLE;
  if (envTitle) {
    return { title: normTitle(envTitle), source: 'env', composerId: null };
  }

  const headers = loadComposerHeaders();
  const composer = pickComposer(headers, opts);
  if (composer?.name) {
    const payload = {
      composerId: composer.composerId,
      title: normTitle(composer.name),
      workspace: composer.workspaceIdentifier?.configPath?.fsPath || opts.workspace || '',
    };
    writeActiveVertical(payload);
    return {
      title: payload.title,
      source: 'vscdb',
      composerId: composer.composerId,
    };
  }

  return { title: '', source: 'missing', composerId: null };
}

module.exports = {
  resolveCursorTabTitle,
  writeActiveVertical,
  readActiveVertical,
  ACTIVE_VERTICAL,
  normTitle,
};
