"use strict";
/**
 * Morning Priority store.
 *
 * Persists a single "top priority for today" answer per day under
 * `.harness/priorities/<YYYY-MM-DD>.json`. The 9am trigger reads
 * today's file to decide whether to surface the prompt and, if the
 * user replies via chat / Telegram, the chat handler calls
 * `setPriorityForToday` to store the answer.
 *
 * Read by `composeDailyBrief` via `loadMorningPriorityInputs` so the
 * brief opens with the day's anchor question.
 */
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.todayDate = todayDate;
exports.setPriorityForToday = setPriorityForToday;
exports.markPromptShown = markPromptShown;
exports.getPriorityForToday = getPriorityForToday;
exports.listRecentPriorities = listRecentPriorities;
exports.loadMorningPriorityInputs = loadMorningPriorityInputs;
exports.parsePrioritySetCommand = parsePrioritySetCommand;
const fs = __importStar(require("node:fs/promises"));
const path = __importStar(require("node:path"));
function priorityDir(projectDir) {
    return path.join(projectDir, '.harness', 'priorities');
}
function priorityFile(projectDir, date) {
    return path.join(priorityDir(projectDir), `${date}.json`);
}
function todayDate(now = new Date()) {
    const y = now.getFullYear();
    const m = String(now.getMonth() + 1).padStart(2, '0');
    const d = String(now.getDate()).padStart(2, '0');
    return `${y}-${m}-${d}`;
}
async function readPriority(projectDir, date) {
    try {
        const raw = await fs.readFile(priorityFile(projectDir, date), 'utf-8');
        return JSON.parse(raw);
    }
    catch {
        return null;
    }
}
async function writePriority(projectDir, p) {
    await fs.mkdir(priorityDir(projectDir), { recursive: true });
    await fs.writeFile(priorityFile(projectDir, p.date), JSON.stringify(p, null, 2), 'utf-8');
}
/** Set today's top priority. */
async function setPriorityForToday(projectDir, answer, now = new Date()) {
    const date = todayDate(now);
    const existing = (await readPriority(projectDir, date)) ?? { date };
    const stored = { ...existing, date, answer: answer.trim(), setAt: now.toISOString() };
    await writePriority(projectDir, stored);
    return stored;
}
/** Record that the prompt was shown today (so the trigger can dedupe). */
async function markPromptShown(projectDir, now = new Date()) {
    const date = todayDate(now);
    const existing = (await readPriority(projectDir, date)) ?? { date };
    const stored = { ...existing, date, askedAt: now.toISOString() };
    await writePriority(projectDir, stored);
    return stored;
}
/** Read today's priority (or null if unset). */
async function getPriorityForToday(projectDir, now = new Date()) {
    return readPriority(projectDir, todayDate(now));
}
/** List recent priorities, newest-first, capped. */
async function listRecentPriorities(projectDir, limit = 7) {
    const dir = priorityDir(projectDir);
    let entries;
    try {
        entries = await fs.readdir(dir);
    }
    catch {
        return [];
    }
    const files = entries.filter((f) => /^\d{4}-\d{2}-\d{2}\.json$/.test(f)).sort().reverse();
    const out = [];
    for (const file of files.slice(0, limit)) {
        try {
            const raw = await fs.readFile(path.join(dir, file), 'utf-8');
            out.push(JSON.parse(raw));
        }
        catch {
            // skip unreadable file
        }
    }
    return out;
}
/**
 * Produce the `MorningPriorityInputs` shape consumed by composeDailyBrief.
 * Returns null when the file does not exist and there's nothing to show.
 */
async function loadMorningPriorityInputs(projectDir, now = new Date()) {
    const date = todayDate(now);
    const today = await readPriority(projectDir, date);
    const recent = await listRecentPriorities(projectDir, 6);
    const filteredRecent = recent
        .filter((p) => p.date !== date && p.answer)
        .map((p) => ({ date: p.date, answer: p.answer }));
    if (!today && filteredRecent.length === 0)
        return null;
    return {
        forDate: date,
        answer: today?.answer,
        recentPriorities: filteredRecent,
    };
}
/**
 * Recognise a chat message that sets today's priority. Returns the
 * extracted answer string when matched, else null.
 *
 * Accepts (case-insensitive):
 *   priority: deploy v2 to prod
 *   /priority deploy v2 to prod
 *   top priority: deploy v2 to prod
 */
function parsePrioritySetCommand(message) {
    const trimmed = message.trim();
    // /priority allows space or colon; "priority" and "top priority" require a colon.
    const m = trimmed.match(/^(?:\/priority[:\s]+|(?:top\s+)?priority\s*:\s*)(.+)$/i);
    if (m && m[1].trim())
        return m[1].trim();
    return null;
}
//# sourceMappingURL=morningPriority.js.map