"use strict";
/**
 * docuflow recent
 *
 * Shows a dashboard of recent activity:
 *   - Recent git commits (last N days)
 *   - Recent wiki activity from .docuflow/log.md
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.run = run;
const promises_1 = __importDefault(require("node:fs/promises"));
const node_path_1 = __importDefault(require("node:path"));
const node_child_process_1 = require("node:child_process");
// ── ANSI helpers ──────────────────────────────────────────────────────────────
const c = {
    dim: (s) => `\x1b[2m${s}\x1b[0m`,
    bold: (s) => `\x1b[1m${s}\x1b[0m`,
    cyan: (s) => `\x1b[36m${s}\x1b[0m`,
};
function formatDateYMD(d) {
    return d.toISOString().slice(0, 10);
}
// ── Git commits (recent, date-filtered) ──────────────────────────────────────
function recentCommits(days) {
    try {
        const out = (0, node_child_process_1.execSync)(`git log --oneline --since="${days} days ago"`, { encoding: "utf8", stdio: ["pipe", "pipe", "ignore"] });
        return out.trim().split("\n").filter(Boolean);
    }
    catch {
        return [];
    }
}
// ── Wiki log parsing ──────────────────────────────────────────────────────────
const headingRe = /^##\s+\[([^\]]+)\]\s+([^|]+?)(?:\s*\|\s*(.+))?$/;
async function parseWikiLog(logPath, since) {
    let content;
    try {
        content = await promises_1.default.readFile(logPath, "utf8");
    }
    catch {
        return [];
    }
    const entries = [];
    for (const line of content.split("\n")) {
        const m = headingRe.exec(line.trim());
        if (!m) {
            // Legacy pipe-delimited: timestamp | tool | target | delta
            const parts = line.split("|").map(p => p.trim());
            if (parts.length >= 3 && parts[0].includes("T")) {
                const d = new Date(parts[0]);
                if (!isNaN(d.getTime()) && d >= since) {
                    entries.push({ date: formatDateYMD(d), operation: parts[1] ?? "", file: parts[2] ?? "" });
                }
            }
            continue;
        }
        const d = new Date(m[1]);
        if (isNaN(d.getTime()) || d < since)
            continue;
        entries.push({ date: formatDateYMD(d), operation: (m[2] ?? "").trim(), file: (m[3] ?? "").trim() });
    }
    return entries;
}
// ── Renderers ─────────────────────────────────────────────────────────────────
function renderTable(commits, wikiEntries, days) {
    const fromDate = formatDateYMD(new Date(Date.now() - days * 86400000));
    const toDate = formatDateYMD(new Date());
    console.log("");
    console.log(c.bold(`DocuFlow — Recent Activity (${fromDate} → ${toDate})`));
    console.log("");
    console.log(c.bold(`Git Commits (last ${days} days)`));
    console.log("─".repeat(60));
    if (commits.length === 0) {
        console.log(c.dim("  No commits in this period."));
    }
    else {
        for (const line of commits) {
            const sha = line.slice(0, 7);
            const msg = line.slice(8);
            console.log(`  ${c.cyan(sha)}  ${msg}`);
        }
    }
    console.log("");
    console.log(c.bold(`Wiki Activity (last ${days} days)`));
    console.log("─".repeat(60));
    if (wikiEntries.length === 0) {
        console.log(c.dim("  No wiki activity in this period."));
    }
    else {
        for (const e of wikiEntries) {
            console.log(`  ${c.dim(e.date)}  ${e.operation}${e.file ? "  " + c.dim(e.file) : ""}`);
        }
    }
    console.log("");
}
function renderMarkdown(commits, wikiEntries, days) {
    const fromDate = formatDateYMD(new Date(Date.now() - days * 86400000));
    const toDate = formatDateYMD(new Date());
    console.log(`# DocuFlow — Recent Activity (${fromDate} → ${toDate})`);
    console.log("");
    console.log(`## Git Commits (last ${days} days)`);
    console.log("");
    if (commits.length === 0) {
        console.log("_No commits in this period._");
    }
    else {
        for (const line of commits) {
            console.log(`- ${line}`);
        }
    }
    console.log("");
    console.log(`## Wiki Activity (last ${days} days)`);
    console.log("");
    if (wikiEntries.length === 0) {
        console.log("_No wiki activity in this period._");
    }
    else {
        console.log("| Date | Operation | File |");
        console.log("|------|-----------|------|");
        for (const e of wikiEntries) {
            console.log(`| ${e.date} | ${e.operation} | ${e.file} |`);
        }
    }
}
// ── Main entry point ──────────────────────────────────────────────────────────
async function run(opts = { days: 7, format: "table" }) {
    const days = Math.max(1, isNaN(opts.days) ? 7 : opts.days);
    const format = opts.format ?? "table";
    const cwd = process.cwd();
    const logPath = node_path_1.default.join(cwd, ".docuflow", "log.md");
    const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
    const commits = recentCommits(days);
    const wikiEntries = await parseWikiLog(logPath, since);
    if (format === "md") {
        renderMarkdown(commits, wikiEntries, days);
    }
    else {
        renderTable(commits, wikiEntries, days);
    }
}
