"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.previewBasicTaskPairCreationSync = exports.applyBasicTaskPairCreationSync = exports.BasicTaskCreationError = void 0;
exports.renderStructuredTaskDefinition = renderStructuredTaskDefinition;
exports.renderStructuredImplementationSummary = renderStructuredImplementationSummary;
exports.structuredRuntimeContractFields = structuredRuntimeContractFields;
exports.structuredCriterionId = structuredCriterionId;
exports.renderSharedStructuredTemplate = renderSharedStructuredTemplate;
exports.insertTopLevelFrontMatterFields = insertTopLevelFrontMatterFields;
exports.insertBodySectionBefore = insertBodySectionBefore;
exports.readRequiredTemplate = readRequiredTemplate;
exports.requireRepositoryRelativeInput = requireRepositoryRelativeInput;
exports.requireText = requireText;
exports.normalizeRecordedRevision = normalizeRecordedRevision;
exports.optionalText = optionalText;
exports.requireStringList = requireStringList;
exports.titleFromSlug = titleFromSlug;
exports.bulletList = bulletList;
exports.collectStructuredSourceImplementationOrderEvidence = collectStructuredSourceImplementationOrderEvidence;
exports.normalizeOrderedRootCreationError = normalizeOrderedRootCreationError;
exports.inventoryConflict = inventoryConflict;
// Structured and governed overview plus task-pair creation orchestration.
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const cli_constants_1 = require("../config/cli-constants");
const canonical_write_target_1 = require("../paths/canonical-write-target");
const ordered_root_identity_1 = require("../planning/ordered-root-identity");
const planning_document_utils_1 = require("../planning/planning-document-utils");
const spec_registry_1 = require("../spec-registry");
const path_resolution_1 = require("../templates/path-resolution");
const creation_overview_1 = require("./creation-overview");
const governed_overview_1 = require("./governed-overview");
function renderStructuredTaskDefinition(template, input) {
    const runtimeDelta = [
        `- Runtime target files: ${input.task.targetPaths.map((value) => `\`${value}\``).join(", ")}.`,
        `- Expected behavior change: ${input.task.desiredBehavior}`,
        `- Verification commands with expected evidence: ${input.task.validationCommands.map((value) => `\`${value}\``).join(", ")}.`,
        `- Rollback path: ${input.task.rollbackRecovery}`
    ].join("\n");
    let text = renderSharedStructuredTemplate(template, {
        overview: input.overview,
        overviewPath: input.overviewPath,
        entry: input.entry,
        generatedAt: input.generatedAt,
        titleSuffix: "",
        replacements: {
            "{{objective}}": input.task.objective,
            "{{upstream_context}}": `- Parent Structured overview: \`${input.overviewPath}\`.`,
            "{{target_paths}}": bulletList(input.task.targetPaths),
            "{{current_behavior}}": input.task.currentBehavior,
            "{{desired_behavior}}": input.task.desiredBehavior,
            "{{runtime_delta}}": runtimeDelta,
            "{{acceptance_criteria}}": bulletList(input.task.acceptanceCriteria),
            "{{validation_commands}}": `\`\`\`sh\n${input.task.validationCommands.join("\n")}\n\`\`\``,
            "{{rollback_recovery}}": input.task.rollbackRecovery,
            "{{risks}}": "- Task implementation must preserve the explicit Structured parent and declared dependency order.",
            "{{dependencies}}": input.dependencyPaths.length === 0 ? "- None." : bulletList(input.dependencyPaths),
            "{{constraints}}": input.task.constraints.length === 0 ? "- None." : bulletList(input.task.constraints),
            "{{assumptions}}": "- The parent overview and source specification revisions remain current through apply.",
            "{{lifecycle_closure_expectations}}": "Complete the paired implementation summary with changed paths, acceptance results, and executable validation evidence before explicit review and closeout.",
            "{{open_questions}}": "- None currently."
        }
    });
    text = insertTopLevelFrontMatterFields(text, input.entry.dependencies.length === 0
        ? [
            ...structuredRuntimeContractFields(input.entry, input.task.acceptanceCriteria.length),
            `sequence: ${input.entry.sequence}`,
            "depends_on: []"
        ]
        : [
            ...structuredRuntimeContractFields(input.entry, input.task.acceptanceCriteria.length),
            `sequence: ${input.entry.sequence}`,
            "depends_on:",
            ...input.entry.dependencies.map((dependency) => `  - ${(0, governed_overview_1.yamlString)(dependency)}`)
        ]);
    if (input.sourceProjectReviewPath !== null) {
        text = insertBodySectionBefore(text, "Open Questions", [
            "## Follow-Up Origin",
            "",
            `Declared by canonical Structured project review \`${input.sourceProjectReviewPath}\`.`,
            ""
        ]);
    }
    return text;
}
function renderStructuredImplementationSummary(template, input) {
    const text = renderSharedStructuredTemplate(template, {
        overview: input.overview,
        overviewPath: input.overviewPath,
        entry: input.entry,
        generatedAt: input.generatedAt,
        titleSuffix: "",
        replacements: {
            "{{summary}}": "Pending. Record implementation outcomes after the task is executed.",
            "{{changed_paths}}": "None yet.",
            "{{acceptance_criteria_results}}": "Pending review after implementation.",
            "{{validation_performed}}": "None yet.",
            "{{validation_exceptions}}": "None.",
            "{{scope_classification}}": "Not started. Expected scope is limited to the task definition.",
            "{{runtime_evidence_boundary}}": `Pending runtime evidence for evidence_profile \`${input.entry.evidenceProfile}\`.`,
            "{{deviations}}": "None yet.",
            "{{risks_and_follow_ups}}": "Pending implementation review.",
            "{{open_questions}}": "- None currently."
        }
    });
    return insertTopLevelFrontMatterFields(text, structuredRuntimeContractFields(input.entry, input.task.acceptanceCriteria.length));
}
function structuredRuntimeContractFields(entry, criterionCount) {
    const required = entry.evidenceProfile === "runtime" || entry.evidenceProfile === "hybrid";
    const fields = [
        `runtime_attribution_required: ${required}`,
        "runtime_acceptance:",
        `  required: ${required}`
    ];
    if (!required) {
        fields.push("  criterion_ids: []");
        return fields;
    }
    fields.push("  criterion_ids:");
    for (let index = 0; index < criterionCount; index += 1) {
        fields.push(`    - ${structuredCriterionId(entry.taskId, index)}`);
    }
    return fields;
}
function structuredCriterionId(taskId, index) {
    return `STRUCTURED-${taskId.toUpperCase().replace(/-/g, "_")}-AC-${String(index + 1).padStart(2, "0")}`;
}
function renderSharedStructuredTemplate(template, input) {
    const specsBlock = input.overview.specifications.flatMap((specification) => [
        `    - id: ${(0, governed_overview_1.yamlString)(specification.specId)}`,
        `      ref: ${(0, governed_overview_1.yamlString)(specification.specPath)}`,
        `      revision: ${(0, governed_overview_1.yamlString)(specification.revision)}`
    ]).join("\n");
    let text = template.replace([
        "  specs:",
        "    - id: \"{{spec_id}}\"",
        "      depth: \"{{spec_depth}}\"",
        "      ref: \"{{spec_ref}}\"",
        "      source_type: \"{{source_type}}\""
    ].join("\n"), `  specs:\n${specsBlock}`);
    const standard = {
        "{{task}}": input.entry.taskId,
        "{{task_title}}": `${input.entry.title}${input.titleSuffix}`,
        "{{slice}}": "structured",
        "{{phase}}": input.overview.workId,
        "{{milestone}}": "direct-tasks",
        "{{planning_depth}}": "standard",
        "{{workflow_provenance}}": "cli",
        "{{workflow_cli_command}}": `day-shift work task create --overview ${input.overviewPath}`,
        "{{workflow_manual_exception}}": "",
        "{{workflow_level}}": "structured",
        "{{agent_mode}}": input.entry.agentMode,
        "{{evidence_profile}}": input.entry.evidenceProfile,
        "{{created_at}}": input.generatedAt,
        "{{updated_at}}": input.generatedAt,
        "{{slice_overview}}": "",
        "{{phase_overview}}": "",
        "{{milestone_overview}}": input.overviewPath,
        "{{task_definition}}": input.entry.taskDefinitionPath,
        ...input.replacements
    };
    for (const [token, replacement] of Object.entries(standard)) {
        text = text.split(token).join(replacement);
    }
    const lines = text.split(/\r?\n/).filter((line) => !/^(slice|phase|milestone):/.test(line)
        && !/^ {2}(slice_overview|phase_overview|milestone_overview):/.test(line)
        && line.trim() !== "-");
    const upstreamIndex = lines.findIndex((line) => line === "upstream:");
    const specsIndex = lines.findIndex((line, index) => index > upstreamIndex && line === "  specs:");
    if (specsIndex < 0) {
        throw new creation_overview_1.StructuredWorkCreationError("invalid-request", "Shared task template is missing upstream specs.");
    }
    lines.splice(specsIndex, 0, `  work_overview: ${(0, governed_overview_1.yamlString)(input.overviewPath)}`);
    return `${lines.join("\n").trimEnd()}\n`;
}
function insertTopLevelFrontMatterFields(markdownText, fields) {
    const lines = markdownText.split(/\r?\n/);
    const closingIndex = lines.findIndex((line, index) => index > 0 && line === "---");
    if (closingIndex < 0)
        throw new creation_overview_1.StructuredWorkCreationError("invalid-request", "Rendered task template is malformed.");
    lines.splice(closingIndex, 0, ...fields);
    return lines.join("\n");
}
function insertBodySectionBefore(markdownText, heading, sectionLines) {
    const lines = markdownText.split(/\r?\n/);
    const index = lines.findIndex((line) => line === `## ${heading}`);
    if (index < 0) {
        throw new creation_overview_1.StructuredWorkCreationError("invalid-request", `Rendered task template is missing '${heading}'.`);
    }
    lines.splice(index, 0, ...sectionLines);
    return lines.join("\n");
}
function readRequiredTemplate(repositoryRoot, templatePath) {
    const absolutePath = (0, path_resolution_1.resolveWorkspaceTemplateAbsolutePath)({ repositoryRoot, templatePath });
    if (!node_fs_1.default.existsSync(absolutePath) || !node_fs_1.default.statSync(absolutePath).isFile()) {
        throw new creation_overview_1.StructuredWorkCreationError("invalid-request", `Shared template '${templatePath}' is missing.`);
    }
    return node_fs_1.default.readFileSync(absolutePath, "utf8");
}
function requireRepositoryRelativeInput(value, label) {
    const normalized = value.trim().replace(/\\/g, "/");
    if (normalized === "" || node_path_1.default.posix.isAbsolute(normalized) || normalized.split("/").includes("..")) {
        throw new creation_overview_1.StructuredWorkCreationError("invalid-request", `${label} must be repository-relative and contained.`);
    }
    return normalized.replace(/^\.\//, "");
}
function requireText(value, label) {
    if (typeof value !== "string" || value.trim() === "") {
        throw new creation_overview_1.StructuredWorkCreationError("invalid-request", `${label} must be a non-empty string.`);
    }
    return value.trim();
}
function normalizeRecordedRevision(value) {
    return value.startsWith("sha256:") ? value.slice("sha256:".length) : value;
}
function optionalText(value) {
    return typeof value === "string" && value.trim() !== "" ? value.trim() : null;
}
function requireStringList(value, label, nonEmpty) {
    if (!Array.isArray(value) || nonEmpty && value.length === 0) {
        throw new creation_overview_1.StructuredWorkCreationError("invalid-request", `${label} must be ${nonEmpty ? "a non-empty" : "an"} array of strings.`);
    }
    return value.map((entry) => requireText(entry, label));
}
function titleFromSlug(slug) {
    return slug.split("-").map((part) => `${part.charAt(0).toUpperCase()}${part.slice(1)}`).join(" ");
}
function bulletList(values) {
    return values.map((value) => `- ${value}`).join("\n");
}
function collectStructuredSourceImplementationOrderEvidence(repositoryRoot, specifications) {
    const registryPath = cli_constants_1.CLI_SPEC_INDEX_PATH;
    const registryTarget = (0, canonical_write_target_1.resolveCanonicalWriteTargetSync)(repositoryRoot, registryPath);
    let entries = [];
    if (registryTarget.exists && node_fs_1.default.statSync(registryTarget.runtimePath).isFile()) {
        try {
            entries = (0, spec_registry_1.parseSpecIndexDocumentText)(node_fs_1.default.readFileSync(registryTarget.runtimePath, "utf8")).entries;
        }
        catch (error) {
            throw new creation_overview_1.StructuredWorkCreationError("invalid-request", `Structured creation could not parse source-order registry evidence: ${error instanceof Error ? error.message : String(error)}`);
        }
    }
    const orders = [];
    for (const specification of specifications) {
        const evidence = [];
        const registryEntry = entries.find((entry) => entry.id === specification.specId && entry.spec_path === specification.specPath);
        if (registryEntry?.optional.implementation_order !== undefined) {
            evidence.push((0, ordered_root_identity_1.normalizeImplementationOrder)(registryEntry.optional.implementation_order, `Specification '${specification.specId}' registry implementation_order`));
        }
        const specificationTarget = (0, canonical_write_target_1.resolveCanonicalWriteTargetSync)(repositoryRoot, specification.specPath);
        if (specificationTarget.exists && node_fs_1.default.statSync(specificationTarget.runtimePath).isFile()) {
            const document = (0, planning_document_utils_1.parseMarkdownFrontMatter)(node_fs_1.default.readFileSync(specificationTarget.runtimePath, "utf8"));
            const frontMatterOrder = (0, planning_document_utils_1.readTopLevelField)(document.frontMatterLines, "implementation_order");
            if (frontMatterOrder !== undefined) {
                evidence.push((0, ordered_root_identity_1.normalizeImplementationOrder)(frontMatterOrder, `Specification '${specification.specId}' front-matter implementation_order`));
            }
        }
        const distinct = [...new Set(evidence)];
        if (distinct.length > 1) {
            throw new creation_overview_1.StructuredWorkCreationError("invalid-request", `Specification '${specification.specId}' has conflicting implementation_order evidence: ${distinct.join(", ")}.`);
        }
        orders.push(...distinct);
    }
    return {
        orders,
        registryPath: registryTarget.exists ? registryPath : null
    };
}
function normalizeOrderedRootCreationError(error) {
    if (error instanceof creation_overview_1.StructuredWorkCreationError)
        return error;
    if (error instanceof ordered_root_identity_1.OrderedRootIdentityError) {
        const conflictCodes = new Set([
            "duplicate-stable-identity",
            "duplicate-implementation-order",
            "duplicate-task-sequence",
            "identity-mismatch",
            "order-mismatch",
            "inventory-incomplete"
        ]);
        return new creation_overview_1.StructuredWorkCreationError(conflictCodes.has(error.code) ? "destination-conflict" : "invalid-request", error.message);
    }
    return new creation_overview_1.StructuredWorkCreationError("invalid-request", error instanceof Error ? error.message : "Ordered-root creation failed.");
}
function inventoryConflict(pathValue, expected, observed) {
    return {
        path: pathValue,
        expectationKind: "content-revision",
        expectedState: expected,
        observedState: observed,
        refreshPreviewRequired: true,
        guidance: "Refresh the preview before retrying this mutation."
    };
}
var basic_task_1 = require("./basic-task");
Object.defineProperty(exports, "BasicTaskCreationError", { enumerable: true, get: function () { return basic_task_1.BasicTaskCreationError; } });
Object.defineProperty(exports, "applyBasicTaskPairCreationSync", { enumerable: true, get: function () { return basic_task_1.applyBasicTaskPairCreationSync; } });
Object.defineProperty(exports, "previewBasicTaskPairCreationSync", { enumerable: true, get: function () { return basic_task_1.previewBasicTaskPairCreationSync; } });
