/*
 * Copyright 2026, Jaime Terrats.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { existsSync, readFileSync, mkdirSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { Hono } from 'hono';
import { getWorkspaceCwd } from '../middleware/workspace.js';
const execFileAsync = promisify(execFile);
const INSIGHTS_DIR = '.setup-agents/insights';
const DASHBOARD_FILE = 'delivery-dashboard.html';
export function insightsRoute(cwd) {
    const app = new Hono();
    // GET / — return cached dashboard HTML or 404
    app.get('/', (c) => {
        const dir = getWorkspaceCwd(c, cwd);
        const dashPath = join(dir, INSIGHTS_DIR, DASHBOARD_FILE);
        if (!existsSync(dashPath)) {
            return c.json({ available: false, html: null, generatedAt: null });
        }
        const html = readFileSync(dashPath, 'utf-8');
        const fstat = statSync(dashPath);
        return c.json({ available: true, html, generatedAt: new Date(fstat.mtimeMs).toISOString() });
    });
    // POST /generate — trigger PM subagent to generate dashboard
    app.post('/generate', async (c) => {
        const dir = getWorkspaceCwd(c, cwd);
        // Ensure insights dir exists
        const insightsDir = join(dir, INSIGHTS_DIR);
        if (!existsSync(insightsDir)) {
            mkdirSync(insightsDir, { recursive: true });
        }
        try {
            const outputPath = join(insightsDir, DASHBOARD_FILE);
            await execFileAsync('sf', ['setup-agents', 'dashboard', '--output', outputPath], {
                cwd: dir,
                timeout: 60000,
                env: { ...process.env, NODE_ENV: 'production' },
            });
            const dashPath = join(insightsDir, DASHBOARD_FILE);
            if (existsSync(dashPath)) {
                const html = readFileSync(dashPath, 'utf-8');
                return c.json({ success: true, html, generatedAt: new Date().toISOString() });
            }
            return c.json({ success: false, error: 'Dashboard file not generated' }, 500);
        }
        catch (e) {
            const err = e;
            return c.json({ success: false, error: err.stderr ?? err.message }, 500);
        }
    });
    return app;
}
//# sourceMappingURL=insights.js.map