"use strict";
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.generator = exports.generatorId = void 0;
const path = __importStar(require("node:path"));
const Generator = __importStar(require("@postxl/generator"));
const docker_sh_generator_1 = require("./generators/docker-sh.generator");
const model_test_id_generator_1 = require("./generators/model-test-id.generator");
const PACKAGE_JSON_FILENAME = 'package.json';
exports.generatorId = Generator.toGeneratorInterfaceId('e2e');
exports.generator = {
    id: exports.generatorId,
    requires: [exports.generatorId],
    register: (ctx) => {
        ctx.backend.packageJson.devDependencies.push({ packageName: 'c8', version: '^10.1.3' });
        return {
            ...ctx,
            e2e: {
                testIds: [],
            },
        };
    },
    generate: async (context) => {
        const vfs = new Generator.VirtualFileSystem();
        const { projectType, slug } = context.schema;
        const isWorkspace = projectType === 'workspace';
        // Template context with project-type-aware values
        const templateContext = {
            schema: context.schema,
            // For e2e.sh
            monorepoRootExpr: isWorkspace ? '"$(cd "$PROJECT_DIR/../.." && pwd)"' : '"$PROJECT_DIR"',
            dockerWorkDir: isWorkspace ? `/pxl/projects/${slug}/e2e` : '/pxl/e2e',
            e2eArtifactsPath: isWorkspace ? `/projects/${slug}/e2e` : '/e2e',
            nodeShimsCleanup: isWorkspace
                ? 'rm -f /pxl/node_modules/.bin/node /pxl/projects/*/node_modules/.bin/node 2>/dev/null'
                : 'rm -f /pxl/node_modules/.bin/node 2>/dev/null',
            // For run-e2e-tests.md
            cdProjectDir: isWorkspace ? `cd projects/${slug}\n` : '',
            backendPath: isWorkspace ? `projects/${slug}/backend` : 'backend',
            frontendPath: isWorkspace ? `projects/${slug}/frontend` : 'frontend',
        };
        // Load e2e folder, excluding files that need template substitution
        await vfs.loadFolder({
            diskPath: path.resolve(__dirname, './template/e2e'),
            targetPath: '/e2e',
            filter: (filePath) => !filePath.endsWith(PACKAGE_JSON_FILENAME),
        });
        // Load files with template substitution
        const packageJsonContent = await Generator.generateFromTemplate({
            file: path.resolve(__dirname, './template/e2e', PACKAGE_JSON_FILENAME),
            context: templateContext,
        });
        if (packageJsonContent.isErr()) {
            throw new Error(`Failed to generate package.json: ${packageJsonContent.unwrapErr().message}`);
        }
        vfs.write(`/e2e/${PACKAGE_JSON_FILENAME}`, packageJsonContent.unwrap());
        // Generate e2e.sh with project-type-aware paths
        const e2eShContent = await Generator.generateFromTemplate({
            file: path.resolve(__dirname, './template/scripts/e2e.sh'),
            context: templateContext,
        });
        if (e2eShContent.isErr()) {
            throw new Error(`Failed to generate e2e.sh: ${e2eShContent.unwrapErr().message}`);
        }
        vfs.write('/scripts/e2e.sh', e2eShContent.unwrap());
        // Generate run-e2e-tests.md with project-type-aware paths
        const runE2eTestsMdContent = await Generator.generateFromTemplate({
            file: path.resolve(__dirname, './template/.claude/commands/run-e2e-tests.md'),
            context: templateContext,
        });
        if (runE2eTestsMdContent.isErr()) {
            throw new Error(`Failed to generate run-e2e-tests.md: ${runE2eTestsMdContent.unwrapErr().message}`);
        }
        vfs.write('/.claude/commands/run-e2e-tests.md', runE2eTestsMdContent.unwrap());
        // Generate prepare-e2e-tests.md with project-type-aware paths
        const prepareE2eTestsMdContent = await Generator.generateFromTemplate({
            file: path.resolve(__dirname, './template/.claude/commands/prepare-e2e-tests.md'),
            context: templateContext,
        });
        if (prepareE2eTestsMdContent.isErr()) {
            throw new Error(`Failed to generate prepare-e2e-tests.md: ${prepareE2eTestsMdContent.unwrapErr().message}`);
        }
        vfs.write('/.claude/commands/prepare-e2e-tests.md', prepareE2eTestsMdContent.unwrap());
        // write dynamic files
        vfs.write('/e2e/support/model-test-ids.ts', (0, model_test_id_generator_1.generateModelTestIds)(context.e2e));
        vfs.write('/scripts/docker.sh', (0, docker_sh_generator_1.generateDockerSh)(context));
        context.vfs.insertFromVfs({ vfs, targetPath: '/' });
        return context;
    },
};
//# sourceMappingURL=e2e.generator.js.map