"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.GeminiAdapter = void 0;
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
const crypto = __importStar(require("crypto"));
// ── Helpers ─────────────────────────────────────────────────────────────────
const GEMINI_HOME = path.join(os.homedir(), '.gemini');
const CCWEB_MARKER = '# ccweb-hook';
/** Replicate Gemini CLI's project hash (SHA-256 of normalized path, first 16 hex chars) */
function getProjectHash(folderPath) {
    const normalized = path.resolve(folderPath);
    return crypto.createHash('sha256').update(normalized).digest('hex').slice(0, 16);
}
function getChatsDir(folderPath) {
    return path.join(GEMINI_HOME, 'tmp', getProjectHash(folderPath), 'chats');
}
function extractParts(parts) {
    if (!parts)
        return [];
    return Array.isArray(parts) ? parts : (parts.parts ?? []);
}
function extractPartsText(parts) {
    return extractParts(parts)
        .filter((p) => p.text && !p.thought)
        .map((p) => p.text.trim())
        .join('\n')
        .trim();
}
function partsToBlocks(parts) {
    const arr = extractParts(parts);
    const blocks = [];
    for (const p of arr) {
        if (p.thought && p.text?.trim()) {
            blocks.push({ type: 'thinking', content: p.text.trim() });
        }
        else if (p.text?.trim()) {
            blocks.push({ type: 'text', content: p.text.trim() });
        }
        else if (p.functionCall) {
            const args = p.functionCall.args ? JSON.stringify(p.functionCall.args).slice(0, 200) : '';
            blocks.push({ type: 'tool_use', content: `${p.functionCall.name}(${args})` });
        }
        else if (p.functionResponse) {
            const out = p.functionResponse.response
                ? JSON.stringify(p.functionResponse.response).slice(0, 200)
                : '';
            blocks.push({ type: 'tool_result', content: out });
        }
    }
    return blocks;
}
/** Parse a Gemini session JSON string into an array of ChatBlocks (all messages). */
function parseGeminiSessionContent(content) {
    let session;
    try {
        session = JSON.parse(content);
    }
    catch {
        return [];
    }
    if (!session.messages || !Array.isArray(session.messages))
        return [];
    const blocks = [];
    for (const msg of session.messages) {
        const ts = msg.timestamp ?? session.startTime ?? '';
        // Prefer displayContent over content if available
        const source = msg.displayContent ?? msg.content;
        if (msg.type === 'user') {
            const items = partsToBlocks(source);
            if (items.length > 0)
                blocks.push({ role: 'user', timestamp: ts, blocks: items });
        }
        else if (msg.type === 'gemini') {
            const items = partsToBlocks(source);
            if (items.length > 0)
                blocks.push({ role: 'assistant', timestamp: ts, blocks: items });
        }
    }
    return blocks;
}
// ── Adapter ─────────────────────────────────────────────────────────────────
class GeminiAdapter {
    constructor() {
        this.tool = 'gemini';
    }
    // ── Command ─────────────────────────────────────────────────────────────
    buildCommand(permissionMode, continueSession) {
        const cont = continueSession ? ' --resume' : '';
        return permissionMode === 'unlimited'
            ? `gemini --yolo${cont}`
            : `gemini${cont}`;
    }
    supportsContinue() {
        return true;
    }
    // ── Session ─────────────────────────────────────────────────────────────
    getSessionDir(folderPath) {
        // Always return the path (like Claude adapter) — callers check existence themselves
        return getChatsDir(folderPath);
    }
    getSessionFileExtension() {
        return '.json';
    }
    getSessionFilesForProject(folderPath) {
        const dir = getChatsDir(folderPath);
        if (!fs.existsSync(dir))
            return [];
        try {
            return fs.readdirSync(dir)
                .filter((f) => f.endsWith('.json'))
                .map((f) => path.join(dir, f));
        }
        catch {
            return [];
        }
    }
    /** Parse the entire session JSON file into all ChatBlocks. */
    parseSessionFile(content) {
        return parseGeminiSessionContent(content);
    }
    parseLineBlocks(_line) {
        return null;
    }
    // ── Hooks ───────────────────────────────────────────────────────────────
    getHooksSettingsPath() {
        return path.join(GEMINI_HOME, 'settings.json');
    }
    getHookEvents() {
        return ['AfterAgent', 'SessionEnd'];
    }
    /**
     * Gemini CLI hooks receive JSON on stdin and write JSON to stdout.
     * We build a small shell pipeline: read stdin, extract fields with jq,
     * then curl the ccweb API. This avoids relying on env vars that may not exist.
     */
    buildHookCommand(event, portFile) {
        // Gemini hooks pass input on stdin as JSON.
        // Use jq to extract project dir, then curl ccweb.
        return (`jq -r '{ event: "${event}", dir: (.cwd // .projectDir // ""), session: (.sessionId // "") }' | ` +
            `curl -sf -X POST "http://localhost:$(cat ${portFile})/api/hooks" ` +
            `-H "Content-Type: application/json" -d @- || true  ${CCWEB_MARKER}`);
    }
    // ── Model & skills ──────────────────────────────────────────────────────
    getCurrentModel() {
        try {
            const settingsPath = path.join(GEMINI_HOME, 'settings.json');
            const raw = fs.readFileSync(settingsPath, 'utf-8');
            const settings = JSON.parse(raw);
            return settings.model || 'gemini-2.5-pro';
        }
        catch {
            return 'gemini-2.5-pro';
        }
    }
    getAvailableModels() {
        return [
            { key: 'gemini-2.5-pro', label: 'Gemini 2.5 Pro' },
            { key: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash' },
            { key: 'gemini-2.0-flash', label: 'Gemini 2.0 Flash' },
        ];
    }
    getSkills() {
        const builtin = [
            { command: '/help', description: 'Show available commands and usage' },
            { command: '/chat', description: 'Start a new conversation' },
            { command: '/resume', description: 'Resume a previous session' },
            { command: '/restore', description: 'Restore a checkpoint' },
            { command: '/model', description: 'Switch AI model' },
            { command: '/settings', description: 'View or change settings' },
            { command: '/hooks', description: 'Manage hooks' },
            { command: '/compress', description: 'Compress context window' },
            { command: '/tools', description: 'List available tools' },
            { command: '/stats', description: 'Show session statistics' },
            { command: '/quit', description: 'Exit Gemini CLI' },
        ];
        return { builtin, custom: [], plugins: [], mcp: [] };
    }
    // ── Usage ──────────────────────────────────────────────────────────────
    async queryUsage() {
        return {};
    }
    clearUsageCache() { }
    getProjectInstructionsFilename() { return 'AGENTS.md'; }
}
exports.GeminiAdapter = GeminiAdapter;
//# sourceMappingURL=gemini-adapter.js.map