/**
 * Analytics event writer — JSONL append-only with date-based rotation.
 *
 * Writes to ~/.takt/analytics/events/YYYY-MM-DD.jsonl when analytics.enabled = true.
 * Does nothing when disabled.
 */
import { appendFileSync, mkdirSync, existsSync } from 'node:fs';
import { join } from 'node:path';
export class AnalyticsWriter {
    static instance = null;
    enabled = false;
    eventsDir = null;
    constructor() { }
    static getInstance() {
        if (!AnalyticsWriter.instance) {
            AnalyticsWriter.instance = new AnalyticsWriter();
        }
        return AnalyticsWriter.instance;
    }
    static resetInstance() {
        AnalyticsWriter.instance = null;
    }
    /**
     * Initialize writer.
     * @param enabled Whether analytics collection is active
     * @param eventsDir Absolute path to the events directory (e.g. ~/.takt/analytics/events)
     */
    init(enabled, eventsDir) {
        this.enabled = enabled;
        this.eventsDir = eventsDir;
        if (this.enabled) {
            if (!existsSync(this.eventsDir)) {
                mkdirSync(this.eventsDir, { recursive: true });
            }
        }
    }
    isEnabled() {
        return this.enabled;
    }
    /** Append an analytics event to the current day's JSONL file */
    write(event) {
        if (!this.enabled || !this.eventsDir) {
            return;
        }
        const filePath = join(this.eventsDir, `${formatDate(event.timestamp)}.jsonl`);
        appendFileSync(filePath, JSON.stringify(event) + '\n', 'utf-8');
    }
}
function formatDate(isoTimestamp) {
    return isoTimestamp.slice(0, 10);
}
// ---- Module-level convenience functions ----
export function initAnalyticsWriter(enabled, eventsDir) {
    AnalyticsWriter.getInstance().init(enabled, eventsDir);
}
export function resetAnalyticsWriter() {
    AnalyticsWriter.resetInstance();
}
export function isAnalyticsEnabled() {
    return AnalyticsWriter.getInstance().isEnabled();
}
export function writeAnalyticsEvent(event) {
    AnalyticsWriter.getInstance().write(event);
}
//# sourceMappingURL=writer.js.map