/**
 * YAML 配置文件 API 路由
 *
 * 提供 YAML 配置文件的读取和写入功能
 */
import { Router } from 'express';
import { promises as fs } from 'node:fs';
import path from 'node:path';
import { validateToken } from '../middleware/auth.js';
import { createLogger } from '../utils/logger.js';
import { resolveWorkspaceFilePath } from '../utils/path-utils.js';
import { loadYmlWithUpwardSearch, extractAgentConfigOrTemplate, generateEmptyTemplate, autoFillPathInYml } from '../utils/yaml-utils.js';
const log = createLogger('yml-routes');
export const ymlRouter = Router();
/**
 * 读取 YAML 配置文件
 * POST /runtime/read-yml
 */
ymlRouter.post('/read-yml', validateToken, async (req, res) => {
    const { workspacePath, ymlPath } = req.body || {};
    try {
        const { normalizedWorkspace, resolvedTarget } = resolveWorkspaceFilePath(workspacePath, ymlPath, 'vibe-coding/my.yml');
        const providedPathStr = ymlPath ? String(ymlPath).trim() || 'vibe-coding/my.yml' : 'vibe-coding/my.yml';
        if (path.isAbsolute(providedPathStr)) {
            let content = '';
            let exists = true;
            try {
                content = await fs.readFile(resolvedTarget, 'utf-8');
            }
            catch (err) {
                const error = err;
                if (error?.code === 'ENOENT') {
                    exists = false;
                }
                else {
                    throw err;
                }
            }
            // 计算工作目录相对于配置文件所属目录（项目根目录）的相对路径
            const configFileDir = path.dirname(resolvedTarget);
            const projectRootDir = path.dirname(configFileDir);
            let workspaceRelativeToProject = path.relative(projectRootDir, normalizedWorkspace);
            if (workspaceRelativeToProject === '') {
                workspaceRelativeToProject = '.';
            }
            let displayContent;
            let isTemplate = false;
            let projectFromSibling = null;
            if (exists && content) {
                const result = extractAgentConfigOrTemplate(content, workspaceRelativeToProject);
                displayContent = result.content;
                isTemplate = result.isTemplate;
                projectFromSibling = result.projectFromSibling;
            }
            else {
                displayContent = generateEmptyTemplate(workspaceRelativeToProject);
                isTemplate = true;
            }
            res.json({
                ok: true,
                workspacePath: normalizedWorkspace,
                filePath: resolvedTarget,
                exists,
                content: displayContent,
                fullContent: exists ? content : null,
                foundInParent: false,
                isTemplate,
                projectFromSibling,
            });
            return;
        }
        // 相对路径：向上查找配置文件
        const loadResult = await loadYmlWithUpwardSearch(normalizedWorkspace, providedPathStr);
        log.info(`loadResult.content length: ${loadResult.content?.length || 0}`);
        const configFileDir = path.dirname(loadResult.resolvedPath);
        const projectRootDir = path.dirname(configFileDir);
        let workspaceRelativeToProject = path.relative(projectRootDir, normalizedWorkspace);
        if (workspaceRelativeToProject === '') {
            workspaceRelativeToProject = '.';
        }
        let displayContent;
        let isTemplate = false;
        let projectFromSibling = null;
        if (loadResult.content !== null) {
            const result = extractAgentConfigOrTemplate(loadResult.content, workspaceRelativeToProject);
            displayContent = result.content;
            isTemplate = result.isTemplate;
            projectFromSibling = result.projectFromSibling;
        }
        else {
            displayContent = generateEmptyTemplate(workspaceRelativeToProject);
            isTemplate = true;
        }
        log.info(`returning fullContent length: ${loadResult.content?.length || 0}`);
        res.json({
            ok: true,
            workspacePath: normalizedWorkspace,
            filePath: loadResult.resolvedPath,
            exists: loadResult.content !== null,
            content: displayContent,
            fullContent: loadResult.content,
            foundInParent: loadResult.foundInParent,
            matchedAgentPath: loadResult.matchedAgentPath,
            isTemplate,
            projectFromSibling,
        });
    }
    catch (error) {
        const err = error;
        res.status(400).json({ error: err?.message || 'read yml failed' });
    }
});
/**
 * 加载完整的 YAML 文件内容
 * POST /runtime/load-yml
 */
ymlRouter.post('/load-yml', validateToken, async (req, res) => {
    const { workspacePath, ymlPath } = req.body || {};
    try {
        const { normalizedWorkspace, resolvedTarget } = resolveWorkspaceFilePath(workspacePath, ymlPath, 'vibe-coding/my.yml');
        const providedPathStr = ymlPath ? String(ymlPath).trim() || 'vibe-coding/my.yml' : 'vibe-coding/my.yml';
        if (path.isAbsolute(providedPathStr)) {
            let content = null;
            let exists = true;
            try {
                content = await fs.readFile(resolvedTarget, 'utf-8');
                log.info(`绝对路径读取成功: ${resolvedTarget}, 内容长度: ${content.length}`);
            }
            catch (err) {
                const error = err;
                if (error?.code === 'ENOENT') {
                    exists = false;
                    log.info(`绝对路径文件不存在: ${resolvedTarget}`);
                }
                else {
                    throw err;
                }
            }
            res.json({
                ok: true,
                workspacePath: normalizedWorkspace,
                filePath: resolvedTarget,
                exists,
                content: exists ? content : null,
            });
            return;
        }
        const loadResult = await loadYmlWithUpwardSearch(normalizedWorkspace, providedPathStr);
        log.info(`向上查找结果: filePath=${loadResult.resolvedPath}, exists=${loadResult.content !== null}, contentLength=${loadResult.content?.length || 0}`);
        res.json({
            ok: true,
            workspacePath: normalizedWorkspace,
            filePath: loadResult.resolvedPath,
            exists: loadResult.content !== null,
            content: loadResult.content,
            foundInParent: loadResult.foundInParent,
        });
    }
    catch (error) {
        const err = error;
        res.status(400).json({ error: err?.message || 'load yml failed' });
    }
});
/**
 * 写入 YAML 配置文件
 * POST /runtime/write-yml
 */
ymlRouter.post('/write-yml', validateToken, async (req, res) => {
    const { workspacePath, ymlPath, content } = req.body || {};
    if (!content || !String(content).trim()) {
        res.status(400).json({ error: 'content is required' });
        return;
    }
    try {
        const { normalizedWorkspace, resolvedTarget: absoluteOrDefaultTarget } = resolveWorkspaceFilePath(workspacePath, ymlPath, 'vibe-coding/my.yml');
        const providedPathStr = ymlPath ? String(ymlPath).trim() || 'vibe-coding/my.yml' : 'vibe-coding/my.yml';
        if (path.isAbsolute(providedPathStr)) {
            const resolvedTarget = absoluteOrDefaultTarget;
            const configFileDir = path.dirname(resolvedTarget);
            const projectRootDir = path.dirname(configFileDir);
            let workspaceRelativeToProject = path.relative(projectRootDir, normalizedWorkspace);
            if (workspaceRelativeToProject === '') {
                workspaceRelativeToProject = '.';
            }
            const processedContent = autoFillPathInYml(String(content), workspaceRelativeToProject);
            const targetDir = path.dirname(resolvedTarget);
            await fs.mkdir(targetDir, { recursive: true });
            await fs.writeFile(resolvedTarget, processedContent, 'utf-8');
            res.json({
                ok: true,
                workspacePath: normalizedWorkspace,
                filePath: resolvedTarget,
                foundInParent: false,
            });
            return;
        }
        const loadResult = await loadYmlWithUpwardSearch(normalizedWorkspace, providedPathStr);
        const initialTarget = path.resolve(normalizedWorkspace, providedPathStr);
        const resolvedTarget = loadResult.content !== null ? loadResult.resolvedPath : initialTarget;
        const configFileDir = path.dirname(resolvedTarget);
        const projectRootDir = path.dirname(configFileDir);
        let workspaceRelativeToProject = path.relative(projectRootDir, normalizedWorkspace);
        if (workspaceRelativeToProject === '') {
            workspaceRelativeToProject = '.';
        }
        const processedContent = autoFillPathInYml(String(content), workspaceRelativeToProject);
        const targetDir = path.dirname(resolvedTarget);
        await fs.mkdir(targetDir, { recursive: true });
        await fs.writeFile(resolvedTarget, processedContent, 'utf-8');
        res.json({
            ok: true,
            workspacePath: normalizedWorkspace,
            filePath: resolvedTarget,
            foundInParent: loadResult.foundInParent,
            matchedAgentPath: loadResult.matchedAgentPath,
            originalTarget: initialTarget !== resolvedTarget ? initialTarget : undefined,
        });
    }
    catch (error) {
        const err = error;
        res.status(400).json({ error: err?.message || 'write yml failed' });
    }
});
