import { normalizePlatformOrOther } from "zqy-novel-core";
import { access } from "node:fs/promises";
import { join } from "node:path";
import { randomBytes } from "node:crypto";
export function normalizeStudioPlatform(platform) {
    return normalizePlatformOrOther(platform);
}
export function buildStudioBookConfig(body, now) {
    const baseId = deriveStudioBookBaseId(body.title);
    return {
        id: baseId,
        title: body.title,
        platform: normalizeStudioPlatform(body.platform),
        genre: body.genre,
        status: "outlining",
        targetChapters: body.targetChapters ?? 200,
        chapterWordCount: body.chapterWordCount ?? 3000,
        ...(body.language === "en"
            ? { language: "en" }
            : body.language === "zh"
                ? { language: "zh" }
                : {}),
        createdAt: now,
        updatedAt: now,
    };
}
export function deriveStudioBookBaseId(title) {
    return title
        .trim()
        .toLowerCase()
        .replace(/[^a-z0-9\u4e00-\u9fff]/g, "-")
        .replace(/-+/g, "-")
        .replace(/^-+|-+$/g, "")
        .slice(0, 30) || "book";
}
export async function resolveUniqueStudioBookId(projectRoot, title) {
    const baseId = deriveStudioBookBaseId(title);
    if (!await bookExists(projectRoot, baseId))
        return baseId;
    for (let index = 2; index <= 99; index += 1) {
        const candidate = `${baseId}-${index}`;
        if (!await bookExists(projectRoot, candidate))
            return candidate;
    }
    return `${baseId}-${randomBytes(4).toString("hex")}`;
}
async function bookExists(projectRoot, bookId) {
    try {
        await access(join(projectRoot, "books", bookId, "book.json"));
        return true;
    }
    catch {
        return false;
    }
}
function defaultWait(delayMs) {
    return new Promise((resolve) => setTimeout(resolve, delayMs));
}
export async function waitForStudioBookReady(bookId, options = {}) {
    const fetchImpl = options.fetchImpl ?? fetch;
    const wait = options.wait ?? defaultWait;
    const maxAttempts = options.maxAttempts ?? 5;
    const retryDelayMs = options.retryDelayMs ?? 150;
    for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
        const response = await fetchImpl(`/api/v1/books/${encodeURIComponent(bookId)}`);
        if (response.ok) {
            return await response.json();
        }
        if (attempt < maxAttempts && response.status === 404) {
            await wait(retryDelayMs);
            continue;
        }
        break;
    }
    throw new Error(`Book "${bookId}" was not ready after ${maxAttempts} attempts.`);
}
//# sourceMappingURL=book-create.js.map