"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.DreamGoalStore = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
class DreamGoalStore {
    stateDir;
    constructor(stateDir = process.env.OPENLIFE_STATE_DIR || path.join(process.cwd(), '.openlife')) {
        this.stateDir = stateDir;
    }
    setDream(value) {
        return this.set('dream', value);
    }
    setGoal(value) {
        return this.set('goal', value);
    }
    getDream() {
        return this.load().dream;
    }
    getGoal() {
        return this.load().goal;
    }
    /**
     * Phase 2 — snapshot for the goal→mission bridge. `needsCompile` is true
     * when an active goal exists and its value differs from the last compiled
     * value (so the ticker is idempotent: re-running without a goal change is
     * a no-op).
     */
    getActiveGoal() {
        const state = this.load();
        const goal = state.goal?.value;
        const needsCompile = !!goal && goal !== state.lastCompiledGoal;
        return {
            goal,
            dream: state.dream?.value,
            goalUpdatedAt: state.goal?.updatedAt,
            lastCompiledAt: state.lastCompiledAt,
            lastCompiledGoal: state.lastCompiledGoal,
            needsCompile,
        };
    }
    /**
     * Phase 2 — record that the current goal value was compiled into missions.
     * Subsequent getActiveGoal().needsCompile stays false until the goal changes.
     */
    markCompiled(compiledGoal) {
        const state = this.load();
        state.lastCompiledAt = new Date().toISOString();
        state.lastCompiledGoal = compiledGoal;
        this.save(state);
    }
    summary() {
        const state = this.load();
        const dream = state.dream?.value || 'não definido';
        const goal = state.goal?.value || 'não definido';
        return [`Dream atual: ${dream}`, `Goal atual: ${goal}`].join('\n');
    }
    handleSlashCommand(input) {
        const trimmed = input.trim();
        const match = trimmed.match(/^\/(dream|goal)(?:\s+([\s\S]+))?$/i);
        if (!match)
            return null;
        const kind = match[1].toLowerCase();
        const value = (match[2] || '').trim();
        if (!value) {
            const current = kind === 'dream' ? this.getDream() : this.getGoal();
            if (!current) {
                return `${this.label(kind)} ainda não definido. Use /${kind} <texto> para registrar.`;
            }
            return `${this.label(kind)} atual:\n${current.value}\n\nAtualizado em: ${current.updatedAt}`;
        }
        const entry = this.set(kind, value);
        const counterpart = kind === 'dream' ? this.getGoal() : this.getDream();
        const nextHint = kind === 'dream'
            ? 'Use /goal para transformar esse sonho em uma missão executável.'
            : 'Use /dream para ajustar a visão maior por trás deste objetivo.';
        return [
            `${this.label(kind)} registrado ✅`,
            '',
            entry.value,
            '',
            counterpart ? this.summary() : nextHint,
        ].join('\n');
    }
    set(kind, rawValue) {
        const value = rawValue.trim();
        if (!value)
            throw new Error(`${kind}_cannot_be_empty`);
        const state = this.load();
        const entry = { kind, value, updatedAt: new Date().toISOString() };
        state[kind] = entry;
        state.history = [...(state.history || []), entry].slice(-50);
        this.save(state);
        this.appendMarkdown(entry);
        return entry;
    }
    label(kind) {
        return kind === 'dream' ? 'Dream' : 'Goal';
    }
    filePath() {
        return path.join(this.stateDir, 'dream-goal.json');
    }
    load() {
        const file = this.filePath();
        if (!fs.existsSync(file))
            return { history: [] };
        try {
            const parsed = JSON.parse(fs.readFileSync(file, 'utf-8'));
            return { ...parsed, history: parsed.history || [] };
        }
        catch {
            return { history: [] };
        }
    }
    save(state) {
        fs.mkdirSync(this.stateDir, { recursive: true });
        fs.writeFileSync(this.filePath(), JSON.stringify(state, null, 2), 'utf-8');
    }
    appendMarkdown(entry) {
        const dir = path.join(this.stateDir, 'dream-goal');
        fs.mkdirSync(dir, { recursive: true });
        const file = path.join(dir, `${entry.kind}.md`);
        fs.appendFileSync(file, `## /${entry.kind} ${entry.updatedAt}\n\n${entry.value}\n\n`, 'utf-8');
    }
}
exports.DreamGoalStore = DreamGoalStore;
