"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AGENT_ENTRYPOINT_FILE_NAME = exports.LOCAL_CONFIG_FILE_NAME = exports.CONFIG_FILE_NAME = exports.DAY_SHIFT_DIRECTORY_NAME = exports.CLI_DESCRIPTION = exports.CLI_VERSION = exports.CLI_NAME = void 0;
exports.renderRuntimeContractSummary = renderRuntimeContractSummary;
exports.getRuntimeContractDetails = getRuntimeContractDetails;
exports.getRuntimeProvenance = getRuntimeProvenance;
exports.detectRepositoryRoot = detectRepositoryRoot;
exports.createRepositoryContext = createRepositoryContext;
const node_path_1 = __importDefault(require("node:path"));
const node_fs_1 = __importDefault(require("node:fs"));
const output_1 = require("../output");
const runtime_provenance_1 = require("./runtime-provenance");
const RELEASE_METADATA_FILE_NAME = ".day-shift-release.json";
exports.CLI_NAME = "day-shift";
exports.CLI_VERSION = resolveCliVersion();
exports.CLI_DESCRIPTION = "Day Shift CLI for planning workflows, task handoffs, and validation guidance.";
exports.DAY_SHIFT_DIRECTORY_NAME = ".day-shift";
exports.CONFIG_FILE_NAME = "config.toml";
exports.LOCAL_CONFIG_FILE_NAME = "local.toml";
exports.AGENT_ENTRYPOINT_FILE_NAME = "agents.md";
function renderRuntimeContractSummary() {
    const details = getRuntimeContractDetails();
    return [
        (0, output_1.renderTerminalHeading)("Day Shift runtime discovery", "title"),
        (0, output_1.renderTerminalSection)({
            heading: "Runtime",
            headingStyle: "section",
            fields: [
                { label: "CLI", value: exports.CLI_NAME },
                { label: "Description", value: exports.CLI_DESCRIPTION },
                { label: "Entrypoint", value: details.runtime.entrypoint },
                { label: "Command registry", value: details.runtime.commandRegistry },
                { label: "Provenance", value: details.runtime.provenance },
                { label: "Release version", value: details.release?.version ?? "(development)" },
                { label: "Installed command", value: details.release?.installedCommandName ?? exports.CLI_NAME },
                { label: "Runtime model", value: details.release?.runtimeModel ?? "(development)" },
                { label: "Artifact root", value: details.runtime.artifactRoot ?? "(development checkout)" }
            ]
        }),
        "",
        (0, output_1.renderTerminalPathBlock)({
            heading: "Helper surfaces",
            headingStyle: "section",
            label: "Helper",
            paths: details.runtime.sharedHelpers
        }),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Supported formats",
            headingStyle: "section",
            fields: [
                { label: "Default format", value: "text" },
                { label: "Supported formats", value: "text, json" },
                { label: "Global option", value: "--format <format>" }
            ]
        }),
        "",
        (0, output_1.renderTerminalCompactList)({
            heading: "Exit codes",
            headingStyle: "section",
            entries: [
                { label: "success", fields: [{ label: "Code", value: 0 }] },
                { label: "warnings treated as failures", fields: [{ label: "Code", value: 1 }] },
                { label: "error findings", fields: [{ label: "Code", value: 2 }] },
                { label: "usage or non-interactive failure", fields: [{ label: "Code", value: 3 }] },
                { label: "unexpected error", fields: [{ label: "Code", value: 4 }] },
                { label: "invalid config", fields: [{ label: "Code", value: 5 }] }
            ]
        }),
        "",
        "Command handlers delegate reusable behavior to shared library modules."
    ].join("\n");
}
function getRuntimeContractDetails() {
    const release = readRuntimeReleaseMetadata();
    const artifactRoot = release === null ? null : resolveRuntimeReleaseArtifactRoot();
    if (release !== null) {
        return {
            release,
            runtime: {
                entrypoint: "dist/cli/index.js",
                commandRegistry: "dist/cli/commands/index.js",
                sharedHelpers: [
                    "dist/lib/runtime/",
                    "dist/lib/output/",
                    "dist/lib/errors/"
                ],
                provenance: "runtime contract from packaged release metadata",
                artifactRoot
            }
        };
    }
    return {
        release: null,
        runtime: {
            entrypoint: "src/cli/index.ts",
            commandRegistry: "src/cli/commands/index.ts",
            sharedHelpers: [
                "src/lib/runtime/",
                "src/lib/output/",
                "src/lib/errors/"
            ],
            provenance: "runtime contract from src/lib/runtime/runtime-contract.ts",
            artifactRoot: null
        }
    };
}
function getRuntimeProvenance() {
    return (0, runtime_provenance_1.createRuntimeProvenance)({
        runtimeRoot: resolveRuntimePackageRoot(),
        runtimeModulePath: __filename,
        cliVersion: exports.CLI_VERSION,
        releaseMetadataPresent: readRuntimeReleaseMetadata() !== null
    });
}
/**
 * Resolve the repository root using the five-step detection order defined in
 * `.day-shift/specs/01-foundation/repository-detection.md`.
 *
 * Steps (in priority order):
 *   1. Explicit `--repo-root` option — skips traversal entirely.
 *   2. Nearest ancestor containing `.day-shift/config.toml`.
 *   3. Nearest ancestor containing `.day-shift/agents.md`.
 *   4. Nearest ancestor containing `.git`.
 *   5. Current working directory (fallback).
 *
 * Each marker-based step searches all ancestor directories independently.
 * A match for a higher-priority marker at any ancestor level takes
 * precedence over a closer match for a lower-priority marker.
 * Detection does not require network access.
 */
function detectRepositoryRoot(options) {
    const startDir = options?.cwd ?? process.cwd();
    const explicitRoot = options?.explicitRoot ?? process.env.DAY_SHIFT_REPOSITORY_ROOT;
    if (explicitRoot !== undefined) {
        return { root: explicitRoot, detectionSource: 'explicit' };
    }
    const markerTypes = [
        { file: node_path_1.default.join(exports.DAY_SHIFT_DIRECTORY_NAME, exports.CONFIG_FILE_NAME), source: 'config-toml' },
        { file: node_path_1.default.join(exports.DAY_SHIFT_DIRECTORY_NAME, exports.AGENT_ENTRYPOINT_FILE_NAME), source: 'agents-md' },
        { file: '.git', source: 'git' },
    ];
    for (const marker of markerTypes) {
        const found = findAncestorWithFile(startDir, marker.file);
        if (found !== null) {
            return { root: found, detectionSource: marker.source };
        }
    }
    return { root: startDir, detectionSource: 'cwd' };
}
/**
 * Create the shared repository-context object used by downstream commands.
 *
 * The root is already resolved before this helper runs. The warning state is
 * supplied by the warning/confirmation layer so commands do not re-evaluate
 * fallback behavior. Optional path fields are derived from the detection source
 * and remain path-only; config parsing and layered config resolution are
 * handled by the shared config contract in `src/lib/config/`.
 */
function createRepositoryContext(detection, warnedAboutFallback) {
    return {
        root: detection.root,
        detectionSource: detection.detectionSource,
        warnedAboutFallback,
        configPath: detection.detectionSource === 'config-toml'
            ? node_path_1.default.join(detection.root, exports.DAY_SHIFT_DIRECTORY_NAME, exports.CONFIG_FILE_NAME)
            : undefined,
        agentEntrypointPath: detection.detectionSource === 'agents-md'
            ? node_path_1.default.join(detection.root, exports.DAY_SHIFT_DIRECTORY_NAME, exports.AGENT_ENTRYPOINT_FILE_NAME)
            : undefined
    };
}
function findAncestorWithFile(startDir, relativePath) {
    let dir = startDir;
    while (true) {
        if (node_fs_1.default.existsSync(node_path_1.default.join(dir, relativePath))) {
            return dir;
        }
        const parent = node_path_1.default.dirname(dir);
        if (parent === dir) {
            return null;
        }
        dir = parent;
    }
}
function resolveCliVersion() {
    const releaseVersion = readRuntimeReleaseMetadata()?.version ?? null;
    return releaseVersion ?? "0.0.0";
}
function readRuntimeReleaseMetadata() {
    const metadataPath = resolveRuntimeReleaseMetadataPath();
    if (!node_fs_1.default.existsSync(metadataPath)) {
        return null;
    }
    try {
        const metadata = JSON.parse(node_fs_1.default.readFileSync(metadataPath, "utf8"));
        if (metadata.schemaVersion !== 1 ||
            typeof metadata.version !== "string" ||
            metadata.version.trim().length === 0 ||
            typeof metadata.installedCommandName !== "string" ||
            metadata.installedCommandName.trim().length === 0 ||
            typeof metadata.runtimeModel !== "string" ||
            metadata.runtimeModel.trim().length === 0) {
            return null;
        }
        return {
            schemaVersion: 1,
            name: typeof metadata.name === "string" ? metadata.name : null,
            version: metadata.version,
            installedCommandName: metadata.installedCommandName,
            runtimeModel: metadata.runtimeModel,
            requiredNodeVersion: typeof metadata.requiredNodeVersion === "string"
                ? metadata.requiredNodeVersion
                : null
        };
    }
    catch {
        return null;
    }
}
function resolveRuntimeReleaseArtifactRoot() {
    return node_path_1.default.dirname(resolveRuntimeReleaseMetadataPath());
}
function resolveRuntimeReleaseMetadataPath() {
    return node_path_1.default.join(resolveRuntimePackageRoot(), RELEASE_METADATA_FILE_NAME);
}
function resolveRuntimePackageRoot() {
    return node_path_1.default.resolve(__dirname, "..", "..", "..");
}
