/**
 * Lightweight local telemetry helpers.
 * Telemetry is emitted only when extension logging is enabled.
 */

import * as logger from "./logger.js";

let runCounter = 0;

/**
 * Telemetry event schema (local-only, debug log output):
 *
 * Required payload fields emitted by this helper:
 * - `event`            : string event name (for example `diagnostics.run`)
 * - `runId`            : unique id for correlating one logical run
 * - `totalDurationMs`  : run wall-clock duration in milliseconds
 * - `tags`             : contextual dimensions (file, lineCount, identifierKind, etc.)
 * - `timingsMs`        : map of phase -> elapsed milliseconds
 * - `counters`         : map of counter -> numeric value
 *
 * Current event names:
 * - `diagnostics.run`      : full document diagnostics pipeline
 * - `include.resolve.sync` : synchronous include symbol resolution
 * - `include.resolve.async`: async include warmup/symbol resolution
 * - `definition.lookup`    : go-to-definition lookup workflow
 *
 * Naming guidance:
 * - Use dotted event names with stable prefixes (`diagnostics.*`, `include.*`, `definition.*`).
 * - Use dotted phase names in `timingsMs` (`validator.function`, `variables.usage`).
 * - Use dotted counter names in `counters` (`cache.hit`, `guard.maxDepth`).
 */
function createTelemetryRun(eventName, tags = {}) {
    if (!logger.isLoggingEnabled()) {
        return;
    }

    const runId = `${Date.now()}-${runCounter++}`;
    const startedAtMs = Date.now();
    const phaseStarts = new Map();
    const timingsMs = new Map();
    const counters = new Map();
    const runTags = { ...tags };

    return {
        runId,
        startPhase(phase) {
            phaseStarts.set(phase, Date.now());
        },
        endPhase(phase) {
            const startedAt = phaseStarts.get(phase);
            if (startedAt === undefined) {
                return;
            }

            phaseStarts.delete(phase);
            const elapsed = Date.now() - startedAt;
            timingsMs.set(phase, (timingsMs.get(phase) || 0) + elapsed);
        },
        increment(counter, delta = 1) {
            counters.set(counter, (counters.get(counter) || 0) + delta);
        },
        setTag(key, value) {
            runTags[key] = value;
        },
        emit(extra = {}) {
            const payload = {
                event: eventName,
                runId,
                totalDurationMs: Date.now() - startedAtMs,
                tags: runTags,
                timingsMs: Object.fromEntries(timingsMs.entries()),
                counters: Object.fromEntries(counters.entries()),
                ...extra
            };

            logger.debug("Telemetry", payload);
        }
    };
}

export {
    createTelemetryRun
};
