/*
 * 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, readdirSync, statSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { homedir } from 'node:os';
import { Hono } from 'hono';
import { listWorkspaces, registerWorkspace, removeWorkspace } from '../../services/workspace-registry.js';
export function workspacesRoute() {
    const app = new Hono();
    // GET /api/v1/workspaces — list all registered workspaces
    // ?includeTmp=true to show temp directory workspaces (for testing)
    app.get('/', (c) => {
        const includeTmp = c.req.query('includeTmp') === 'true';
        const workspaces = listWorkspaces({ includeTempPaths: includeTmp });
        return c.json({ workspaces });
    });
    // POST /api/v1/workspaces/discover — scan common directories for setup-agents projects
    app.post('/discover', (c) => {
        const scanRoots = [join(homedir(), 'dev'), join(homedir(), 'projects'), join(homedir(), 'src')];
        const discovered = [];
        for (const root of scanRoots) {
            if (!existsSync(root))
                continue;
            try {
                const entries = readdirSync(root, { withFileTypes: true });
                for (const entry of entries) {
                    if (!entry.isDirectory())
                        continue;
                    const candidate = join(root, entry.name);
                    if (existsSync(join(candidate, '.setup-agents', 'config.json'))) {
                        registerWorkspace(candidate);
                        discovered.push(candidate);
                    }
                }
            }
            catch {
                // skip unreadable directories
            }
        }
        return c.json({ discovered, total: discovered.length });
    });
    // POST /api/v1/workspaces — register a new workspace
    app.post('/', async (c) => {
        const body = await c.req.json();
        const { path: rawPath } = body;
        if (!rawPath || typeof rawPath !== 'string') {
            return c.json({ error: 'Missing required field: path' }, 400);
        }
        const resolved = resolve(rawPath);
        if (!existsSync(resolved)) {
            return c.json({ error: `Path does not exist: ${resolved}` }, 404);
        }
        try {
            const stat = statSync(resolved);
            if (!stat.isDirectory()) {
                return c.json({ error: `Path is not a directory: ${resolved}` }, 400);
            }
        }
        catch {
            return c.json({ error: `Cannot stat path: ${resolved}` }, 400);
        }
        const entry = registerWorkspace(resolved);
        return c.json({ workspace: entry }, 201);
    });
    // DELETE /api/v1/workspaces — remove a workspace from registry
    app.delete('/', async (c) => {
        const body = await c.req.json();
        const { path: rawPath } = body;
        if (!rawPath || typeof rawPath !== 'string') {
            return c.json({ error: 'Missing required field: path' }, 400);
        }
        const resolved = resolve(rawPath);
        const removed = removeWorkspace(resolved);
        if (!removed) {
            return c.json({ error: `Workspace not found in registry: ${resolved}` }, 404);
        }
        return c.json({ ok: true, removed: resolved });
    });
    return app;
}
//# sourceMappingURL=workspaces.js.map