"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.slugifyPrompt = exports.normalizeWorkspaceRoot = void 0;
exports.kickoffSourceGroundedZeroToOne = kickoffSourceGroundedZeroToOne;
const os_1 = __importDefault(require("os"));
const path_1 = __importDefault(require("path"));
const v3_1 = require("zod/v3");
const generatedDestination_1 = require("./generatedDestination");
// Re-exported for back-compat: tests and other call sites import these from
// here; the canonical definitions now live in `generatedDestination`.
var generatedDestination_2 = require("./generatedDestination");
Object.defineProperty(exports, "normalizeWorkspaceRoot", { enumerable: true, get: function () { return generatedDestination_2.normalizeWorkspaceRoot; } });
Object.defineProperty(exports, "slugifyPrompt", { enumerable: true, get: function () { return generatedDestination_2.slugifyPrompt; } });
const contracts_1 = require("./contracts");
const errors_1 = require("./errors");
const SessionStore_1 = require("./SessionStore");
const sourceContext_1 = require("./sourceContext");
const pinterestSourceContext_1 = require("./pinterestSourceContext");
const DEFAULT_VARIANT_COUNT = 3;
const MIN_VARIANT_COUNT = 2;
const MAX_VARIANT_COUNT = 8;
const proposeVariantsInputSchema = v3_1.z.object(contracts_1.proposeVariantsInput);
const failed = (code, message) => ({
    stage: 'failed',
    errorCode: code,
    message,
});
/**
 * Returns true when a file-copy root is specific enough to authorize asset
 * reads. Broad roots such as the home directory or filesystem root would let
 * an agent-controlled asset plan copy unrelated personal files.
 */
const isSpecificAssetSourceRoot = (root, homePath) => {
    const resolvedRoot = path_1.default.resolve(root);
    return (resolvedRoot !== path_1.default.resolve(homePath) &&
        resolvedRoot !== path_1.default.parse(resolvedRoot).root);
};
/**
 * Run the source-grounded fresh-project kickoff: validate the framework,
 * resolve/normalize inspiration sources, derive the destination, build the
 * `kind:'fresh'` project context (with sourceContext + assetSourceRoot), open
 * the visual editor, and start the source-research flow via
 * `orchestrator.propose`. Returns the multi-step `awaiting_*` stage the agent
 * drives next. Owns its own try/catch so callers can surface the result
 * directly. Called by `start_variants(mode='zero_to_one')` when a session is
 * source-grounded.
 */
async function kickoffSourceGroundedZeroToOne(args, deps) {
    const homedir = deps.homedir ?? os_1.default.homedir;
    try {
        const framework = args.framework ?? 'vite';
        if (framework !== 'vite') {
            return failed('UNSUPPORTED_FRAMEWORK', `Source-grounded zero-to-one only supports framework='vite' in v1; got '${framework}'.`);
        }
        const count = clampCount(args.count);
        const inputSourceUrls = args.sourceContext?.sourceUrls ?? [];
        const sourceUrls = (0, sourceContext_1.resolveSourceUrls)(args.prompt, args.sourceContext);
        // Compare raw inputs in their normalized form so URLs that only differ by
        // hash fragments or trailing punctuation aren't reported as dropped when
        // they were in fact included.
        const resolvedSet = new Set(sourceUrls);
        const droppedUrls = inputSourceUrls.filter((u) => {
            const normalized = (0, sourceContext_1.normalizeUrl)(u);
            return normalized === null || !resolvedSet.has(normalized);
        });
        const warnings = droppedUrls.map((url) => `Skipped source URL '${url}' — failed validation (private network, unsupported scheme, or unreachable).`);
        const inputSourceArtifacts = (0, sourceContext_1.normalizeSourceArtifacts)(args.sourceContext?.sourceArtifacts);
        const projectPath = deps.getProjectPath?.() ?? undefined;
        const cwd = deps.cwd ?? (() => process.cwd());
        // Shared with the prompt-only path: resolve the destination parent (arg →
        // open editor project → cwd), slugify, collapse any nested `.rivet/`, and
        // create `<workspaceRoot>/.rivet/` so the commit-time materialize step has
        // a directory to write into.
        const dest = (0, generatedDestination_1.deriveGeneratedDestination)({
            prompt: args.prompt,
            destinationParent: args.destinationParent,
            editorProjectPath: projectPath,
            cwd,
        });
        if (!dest.ok) {
            return failed(dest.errorCode, dest.message);
        }
        const { workspaceRoot, destinationPath } = dest;
        const assetSourceRoot = projectPath && isSpecificAssetSourceRoot(projectPath, homedir())
            ? path_1.default.resolve(projectPath)
            : undefined;
        const pinterestSourceContext = await (0, pinterestSourceContext_1.enrichPinterestSourceContext)({
            sourceUrls,
            integrationsClient: deps.integrationsClient,
        });
        warnings.push(...pinterestSourceContext.warnings);
        const sourceArtifacts = (0, sourceContext_1.normalizeSourceArtifacts)([
            ...inputSourceArtifacts,
            ...pinterestSourceContext.sourceArtifacts,
        ]);
        const projectContext = {
            kind: 'fresh',
            workspacePath: destinationPath,
            workspaceRoot,
            framework: 'vite',
            ...(assetSourceRoot ? { assetSourceRoot } : {}),
            ...(sourceUrls.length > 0 ||
                sourceArtifacts.length > 0 ||
                args.sourceContext?.preserveBrand !== undefined
                ? {
                    sourceContext: {
                        ...(sourceUrls.length > 0 ? { sourceUrls } : {}),
                        ...(sourceArtifacts.length > 0 ? { sourceArtifacts } : {}),
                        ...(args.sourceContext?.preserveBrand !== undefined
                            ? { preserveBrand: args.sourceContext.preserveBrand }
                            : {}),
                    },
                }
                : {}),
        };
        const proposeInput = {
            sessionId: args.sessionId,
            prompt: args.prompt,
            count,
            projectContext,
        };
        // Validate via the shared schema before delegating, so the proxy and
        // direct callers see the same rejection shape.
        const parsed = proposeVariantsInputSchema.safeParse(proposeInput);
        if (!parsed.success) {
            return failed('SCHEMA_VALIDATION_FAILED', parsed.error.message);
        }
        const visualEditor = deps.ensureVisualEditorOpen
            ? await deps.ensureVisualEditorOpen({
                projectPath: destinationPath,
                workspaceRoot,
                framework: 'vite',
            })
            : undefined;
        const result = deps.orchestrator.propose(parsed.data);
        if (sourceUrls.length > 0 || sourceArtifacts.length > 0) {
            deps.telemetry?.trackAgentVariantsSourceContextQuality?.({
                sessionId: result.sessionId,
                sourceUrlCount: sourceUrls.length,
                artifactCount: sourceArtifacts.length,
                hasScreenshotReferences: sourceArtifacts.some((artifact) => artifact.kind === 'screenshotNotes'),
                preserveBrand: Boolean(args.sourceContext?.preserveBrand),
            });
        }
        if (result.stage === 'awaiting_source_plan') {
            return {
                sessionId: result.sessionId,
                stage: 'awaiting_source_plan',
                sourcePlanWorkItem: {
                    id: result.sourcePlanWorkItem.id,
                    kind: 'source_plan',
                    attempt: result.sourcePlanWorkItem.attempt,
                    input: result.sourcePlanWorkItem.input,
                    output_schema: SessionStore_1.SOURCE_PLAN_OUTPUT_SCHEMA,
                },
                nextAction: 'continue_variants',
                destinationPath,
                ...(visualEditor ? { visualEditor } : {}),
                ...(warnings.length > 0 ? { warnings } : {}),
            };
        }
        return {
            sessionId: result.sessionId,
            stage: 'awaiting_briefs',
            briefWorkItem: {
                id: result.briefWorkItem.id,
                kind: 'brief',
                attempt: result.briefWorkItem.attempt,
                input: result.briefWorkItem.input,
                output_schema: { briefs: 'Array<{briefId, label, body}>' },
            },
            nextAction: 'report_variant_briefs',
            destinationPath,
            ...(visualEditor ? { visualEditor } : {}),
            ...(warnings.length > 0 ? { warnings } : {}),
        };
    }
    catch (err) {
        const code = err instanceof errors_1.AgentVariantsError ? err.code : 'SCHEMA_VALIDATION_FAILED';
        const message = err instanceof Error
            ? err.message
            : 'Unknown error in source-grounded zero-to-one kickoff';
        return { stage: 'failed', errorCode: code, message };
    }
}
const clampCount = (count) => {
    if (count === undefined)
        return DEFAULT_VARIANT_COUNT;
    if (count < MIN_VARIANT_COUNT)
        return MIN_VARIANT_COUNT;
    if (count > MAX_VARIANT_COUNT)
        return MAX_VARIANT_COUNT;
    return count;
};
//# sourceMappingURL=createZeroToOneTool.js.map