"use strict";
/**
 * Prompt Training Data
 *
 * 900+ prompt kütüphanesinden eğitim örnekleri çıkarır.
 * AI prompt generator'a örnek olarak gönderilir.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadTrainingExamples = loadTrainingExamples;
const logger_js_1 = require("../../utils/logger.js");
const file_ops_js_1 = require("../data-store/file-ops.js");
const path_1 = require("path");
const config_js_1 = require("../../utils/config.js");
const log = (0, logger_js_1.createModuleLogger)('prompt-training-data');
let cachedExamples = null;
/**
 * 900+ prompt kütüphanesinden eğitim örnekleri yükler.
 * Opsiyonel kategori filtresi ile belirli kategoriden örnekler alır.
 */
async function loadTrainingExamples(category) {
    if (!cachedExamples) {
        cachedExamples = await buildTrainingExamples();
    }
    let filtered = cachedExamples;
    if (category) {
        // Kategori eşleştirme
        const categoryMap = {
            'selfie-casual': ['casual-everyday', 'selfie'],
            'lifestyle-glamour': ['lifestyle-glamour', 'lifestyle', 'luxury'],
            'nightlife': ['nightlife'],
            'fitness': ['fitness', 'wellness'],
            'beach-pool': ['beach'],
            'intimate-morning': ['intimate-boudoir'],
            'fashion-editorial': ['fashion-editorial', 'fashion'],
            'outdoor-adventure': ['outdoor-adventure', 'travel', 'urban', 'nature'],
        };
        const matchCategories = categoryMap[category] || [category];
        filtered = cachedExamples.filter(ex => matchCategories.includes(ex.category));
    }
    // Rastgele 8 örnek seç
    return shuffleAndPick(filtered.length > 0 ? filtered : cachedExamples, 8);
}
async function buildTrainingExamples() {
    try {
        const promptsPath = (0, path_1.resolve)(config_js_1.config.dataDir, 'prompt-library', 'base-prompts.json');
        const basePrompts = await (0, file_ops_js_1.readJSON)(promptsPath);
        if (!basePrompts || !Array.isArray(basePrompts))
            return [];
        const examples = [];
        for (const bp of basePrompts) {
            try {
                const json = bp.json;
                if (!json)
                    continue;
                const flat = flattenForTraining(json);
                if (!flat.prompt || flat.prompt.length < 50)
                    continue;
                examples.push({
                    id: bp.id,
                    category: bp.category,
                    flatPrompt: flat.prompt,
                    aspectRatio: flat.aspectRatio,
                    outfit: flat.outfit,
                    scene: flat.scene,
                });
            }
            catch {
                // skip malformed prompts
            }
        }
        log.info({ totalExamples: examples.length }, 'Training examples loaded from prompt library');
        return examples;
    }
    catch (err) {
        log.error({ error: err.message }, 'Failed to load training examples');
        return [];
    }
}
/**
 * JSON prompt'u düz eğitim string'ine çevirir.
 * Karakter bilgisi yerine [CHARACTER] placeholder kullanır.
 */
function flattenForTraining(json) {
    const parts = [];
    // Scene
    const scene = extractStr(json, ['scene_type', 'scene', 'setting']);
    if (scene)
        parts.push(scene);
    // Subject placeholder
    parts.push('[CHARACTER]');
    // Action/pose
    const action = extractStr(json, ['subject.action', 'action', 'pose']);
    if (action)
        parts.push(action);
    // Outfit - detaylı çıkar
    const outfit = extractOutfit(json);
    if (outfit)
        parts.push(outfit);
    // Expression
    const expression = extractNested(json, 'expression') || extractNested(json, 'subject.expression');
    if (expression)
        parts.push(expression);
    // Environment
    const env = extractNested(json, 'environment') || extractNested(json, 'setting');
    if (env)
        parts.push(env);
    // Lighting
    const lighting = extractStr(json, ['environment.lighting', 'lighting', 'light']);
    if (lighting)
        parts.push(lighting);
    // Camera/style
    const style = extractStr(json, ['style', 'camera_style', 'aesthetic']);
    if (style)
        parts.push(style);
    // Aspect ratio
    const ar = extractStr(json, ['aspect_ratio', 'camera.aspect_ratio', 'meta.aspect_ratio']) || '9:16';
    return {
        prompt: parts.filter(Boolean).join(', '),
        aspectRatio: ar,
        outfit: outfit || '',
        scene: scene || '',
    };
}
function extractOutfit(json) {
    // Try multiple paths for outfit info
    const paths = ['outfit', 'subject.outfit', 'clothing', 'subject.clothing'];
    for (const path of paths) {
        const val = getNestedValue(json, path);
        if (val && typeof val === 'object') {
            return collectStrings(val).join(', ');
        }
        if (typeof val === 'string' && val.length > 10)
            return val;
    }
    return '';
}
function extractStr(obj, paths) {
    for (const path of paths) {
        const val = getNestedValue(obj, path);
        if (typeof val === 'string' && val.length > 0)
            return val;
    }
    return null;
}
function extractNested(obj, key) {
    const val = getNestedValue(obj, key);
    if (!val)
        return null;
    if (typeof val === 'string')
        return val;
    if (typeof val === 'object') {
        const strings = collectStrings(val);
        return strings.length > 0 ? strings.join(', ') : null;
    }
    return null;
}
function getNestedValue(obj, path) {
    const keys = path.split('.');
    let current = obj;
    for (const key of keys) {
        if (!current || typeof current !== 'object')
            return undefined;
        current = current[key];
    }
    return current;
}
function collectStrings(obj) {
    const results = [];
    if (typeof obj === 'string' && obj.length > 3) {
        results.push(obj);
    }
    else if (Array.isArray(obj)) {
        for (const item of obj) {
            results.push(...collectStrings(item));
        }
    }
    else if (obj && typeof obj === 'object') {
        for (const val of Object.values(obj)) {
            results.push(...collectStrings(val));
        }
    }
    return results;
}
function shuffleAndPick(arr, count) {
    const shuffled = [...arr];
    for (let i = shuffled.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
    }
    return shuffled.slice(0, count);
}
//# sourceMappingURL=prompt-training-data.js.map