"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.assertExecutableScaffoldEvidence = assertExecutableScaffoldEvidence;
exports.assertAcceptanceScopedScaffold = assertAcceptanceScopedScaffold;
exports.normalizeScaffoldDependencyPaths = normalizeScaffoldDependencyPaths;
exports.assertMaterializedRuntimeBreakout = assertMaterializedRuntimeBreakout;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const errors_1 = require("../../errors");
const paths_1 = require("../../paths");
const artifact_policy_projection_1 = require("../artifact-policy-projection");
const front_matter_utils_1 = require("../front-matter-utils");
const artifact_parsing_1 = require("./artifact-parsing");
function assertExecutableScaffoldEvidence(parentPath, evidence) {
    if (evidence.complete)
        return;
    const details = evidence.missingEvidence.map((kind) => `${parentPath}: task '${evidence.childSlug}' is missing ${kind} evidence required for an executable scaffold.`);
    throw (0, errors_1.createInvalidConfigError)(`Planning scaffold refinement is required before task '${evidence.childSlug}' can be created.`, [
        ...details,
        "No task-definition or implementation-summary write was attempted. Add child-scoped Scaffold Evidence or equivalent normalized planning sections, then rerun."
    ], evidence.missingEvidence.map((kind) => ({
        code: `PLANNING_SCAFFOLD_${kind.toUpperCase()}_EVIDENCE_MISSING`,
        message: details.find((entry) => entry.includes(` ${kind} evidence `)) ?? details[0],
        severity: "error",
        path: parentPath,
        evidence: {
            category: "planning-review",
            details: {
                childKind: evidence.childKind,
                childSlug: evidence.childSlug,
                missingEvidenceKind: kind,
                requiresRefinement: true,
                noWriteRequired: true
            }
        }
    })));
}
function assertAcceptanceScopedScaffold(parentPath, evidence) {
    if (evidence.complete)
        return;
    throw (0, errors_1.createInvalidConfigError)(`Acceptance-scoped planning scaffold refinement is required before task '${evidence.childSlug}' can be created.`, [
        ...evidence.issues.map((issue) => `${parentPath}: ${issue.message}`),
        "No task-definition or implementation-summary write was attempted. Refine the selected child's acceptance, behavior, target, validation, rollback, and dependency evidence, then rerun."
    ], evidence.issues.map((issue) => ({
        code: issue.code,
        message: `${parentPath}: ${issue.message}`,
        severity: "error",
        path: parentPath,
        evidence: {
            category: "planning-review",
            details: {
                childKind: "task",
                childSlug: evidence.childSlug,
                evidenceKind: issue.evidenceKind,
                requiresRefinement: true,
                noWriteRequired: true
            }
        }
    })));
}
function normalizeScaffoldDependencyPaths(options) {
    const milestoneDirectory = node_path_1.default.posix.dirname(options.milestoneOverviewPath);
    const normalized = options.dependencies.flatMap((dependency) => {
        const candidate = dependency.trim().replace(/^`|`$/gu, "");
        if (candidate === "" || /\s/u.test(candidate)) {
            return [];
        }
        try {
            const parsed = (0, paths_1.parseRepositoryRelativePath)(candidate);
            if (parsed.segments[0] === "tasks") {
                return [node_path_1.default.posix.join(milestoneDirectory, parsed.normalizedPath)];
            }
            return [parsed.normalizedPath];
        }
        catch {
            return [];
        }
    });
    return [...new Set(normalized)];
}
function assertMaterializedRuntimeBreakout(options) {
    const breakoutTask = options.runtimeAcceptance?.required === true
        ? options.runtimeAcceptance.breakoutTask
        : null;
    if (breakoutTask === null)
        return;
    const taskDirectory = node_path_1.default.join(node_path_1.default.dirname(options.milestoneOverviewPath), "tasks", breakoutTask);
    const taskDefinitionPath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.join(taskDirectory, "task-definition.md"));
    const implementationSummaryPath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.join(taskDirectory, "implementation-summary.md"));
    const taskExists = node_fs_1.default.existsSync(node_path_1.default.join(options.repositoryRoot, taskDefinitionPath));
    const summaryExists = node_fs_1.default.existsSync(node_path_1.default.join(options.repositoryRoot, implementationSummaryPath));
    const breakoutIsCurrentWrite = options.requestedTaskSlug === breakoutTask;
    const breakoutIsPlannedByFullSet = options.validateOnly;
    if (!taskExists && !summaryExists && (breakoutIsCurrentWrite || breakoutIsPlannedByFullSet)) {
        return;
    }
    const issues = [];
    if (!taskExists) {
        issues.push({
            code: "RUNTIME_BREAKOUT_TASK_DEFINITION_MISSING",
            message: `Declared runtime breakout '${breakoutTask}' has no materialized task definition at '${taskDefinitionPath}'.`,
            path: taskDefinitionPath
        });
    }
    if (!summaryExists) {
        issues.push({
            code: "RUNTIME_BREAKOUT_IMPLEMENTATION_SUMMARY_MISSING",
            message: `Declared runtime breakout '${breakoutTask}' has no paired implementation summary at '${implementationSummaryPath}'.`,
            path: implementationSummaryPath
        });
    }
    if (taskExists) {
        const taskText = node_fs_1.default.readFileSync(node_path_1.default.join(options.repositoryRoot, taskDefinitionPath), "utf8");
        const taskFrontMatter = (0, artifact_parsing_1.extractFrontMatter)(taskDefinitionPath, taskText);
        const artifactType = (0, artifact_parsing_1.readTopLevelField)(taskFrontMatter.lines, "artifact_type");
        const taskIdentity = (0, artifact_parsing_1.readTopLevelField)(taskFrontMatter.lines, "task");
        const evidenceProfile = (0, artifact_policy_projection_1.projectArtifactPolicy)(taskText).evidenceProfile;
        if (artifactType !== "task_definition" || taskIdentity !== breakoutTask) {
            issues.push({
                code: "RUNTIME_BREAKOUT_TASK_KIND_MISMATCH",
                message: `Declared runtime breakout path '${taskDefinitionPath}' must identify task_definition '${breakoutTask}', found '${artifactType ?? "(missing)"}' '${taskIdentity ?? "(missing)"}'.`,
                path: taskDefinitionPath
            });
        }
        if (evidenceProfile !== "runtime" && evidenceProfile !== "hybrid") {
            issues.push({
                code: "RUNTIME_BREAKOUT_PROFILE_INCOMPATIBLE",
                message: `Declared runtime breakout '${taskDefinitionPath}' must use evidence_profile runtime or hybrid, found '${evidenceProfile ?? "(missing)"}'.`,
                path: taskDefinitionPath
            });
        }
    }
    if (summaryExists) {
        const summaryText = node_fs_1.default.readFileSync(node_path_1.default.join(options.repositoryRoot, implementationSummaryPath), "utf8");
        const summaryFrontMatter = (0, artifact_parsing_1.extractFrontMatter)(implementationSummaryPath, summaryText);
        const artifactType = (0, artifact_parsing_1.readTopLevelField)(summaryFrontMatter.lines, "artifact_type");
        const taskIdentity = (0, artifact_parsing_1.readTopLevelField)(summaryFrontMatter.lines, "task");
        if (artifactType !== "implementation_summary" || taskIdentity !== breakoutTask) {
            issues.push({
                code: "RUNTIME_BREAKOUT_SUMMARY_KIND_MISMATCH",
                message: `Declared runtime breakout pair '${implementationSummaryPath}' must identify implementation_summary '${breakoutTask}', found '${artifactType ?? "(missing)"}' '${taskIdentity ?? "(missing)"}'.`,
                path: implementationSummaryPath
            });
        }
    }
    if (issues.length === 0)
        return;
    throw (0, errors_1.createInvalidConfigError)(`Runtime breakout ownership rejected '${options.milestoneOverviewPath}' before task writes.`, [
        ...issues.map((issue) => issue.message),
        `Materialize the exact declared breakout with 'day-shift task new --milestone-overview ${options.milestoneOverviewPath} --task-slug ${breakoutTask}' before scaffolding another task.`
    ], issues.map((issue) => ({
        code: issue.code,
        message: issue.message,
        severity: "error",
        path: issue.path,
        evidence: {
            category: "planning-review",
            details: {
                breakoutTask,
                taskDefinitionPath,
                implementationSummaryPath,
                requiresRefinement: true,
                noWriteRequired: true
            }
        }
    })));
}
