import { callLmstudio } from '../lib/lmstudio';
import { logger } from '../lib/logger';
import dotenv from 'dotenv';
import { downloadImagesFromPinterestSearch } from '../lib/pinterest';

dotenv.config();

const PHOTOS_PER_KEYWORD = 10;

// Hard-coded user prompt
const HARDCODED_USER_PROMPT = process.env.HARDCODED_USER_PROMPT || `
    Generate 20 keywords for various photogeneric product. List of 20 most common photo generic product :
    Example output : ["food", "perfume", "accesory", "jewelry", "shoes"...]
    `;

// Re-usable helper to extract JSON embedded in text
function extractJsonFromText(text: string): any | null {
    if (!text || typeof text !== 'string') return null;
    const fenced = text.match(/```(?:json)?\s*([\s\S]*?)\s*```/i);
    if (fenced && fenced[1]) {
        try { return JSON.parse(fenced[1].trim()); } catch (e) { /* fall through */ }
    }
    const brace = text.match(/\{[\s\S]*\}|\[[\s\S]*\]/);
    if (brace && brace[0]) {
        try { return JSON.parse(brace[0]); } catch (e) { return null; }
    }
    // Attempt line-separated keywords fallback
    const lines = text.split(/\r?\n/).map((l: string) => l.trim()).filter(Boolean);
    if (lines.length > 1) return lines;
    return null;
}


(async () => {
    logger.info(`Starting photo download process with prompt: "${HARDCODED_USER_PROMPT}"`);

    // 1. Extract keywords from the hardcoded prompt
    const keywords = ["food", "perfume", "accesory", "jewelry", "shoes", "bags", "watches", "sunglasses", "hats", "scarves", "belts", "wallets", "gloves", "ties", "cufflinks", "brooches", "necklaces", "bracelets", "earrings"];

    if (!keywords || keywords.length === 0) {
        logger.error("Could not extract keywords from prompt. Exiting.");
        return;
    }
    logger.info(`Extracted keywords: ${keywords.join(', ')}`);

    // 2. Search Pinterest for each keyword and download photos directly
    let totalDownloads = 0;
    for (const keyword of keywords) {
        try {
            logger.info(`Downloading photos for keyword: "${keyword}"`);
            const downloadedPaths = await downloadImagesFromPinterestSearch(`${keyword} product photo`, PHOTOS_PER_KEYWORD);
            if (downloadedPaths.length > 0) {
                logger.info(`Successfully downloaded ${downloadedPaths.length} images for "${keyword}"`);
                totalDownloads += downloadedPaths.length;
            } else {
                logger.warn(`No images were downloaded for "${keyword}"`);
            }
        } catch (error) {
            logger.error(`An error occurred while processing keyword ${keyword}:`, error);
        }
    }

    logger.info(`Photo download process finished. Total images downloaded: ${totalDownloads}`);
})();
