const https = require('https');
const http = require('http');
const fs = require('fs');
const express = require('express');
const cors = require('cors');
const OpenAI = require('openai');
const dotenv = require('dotenv');

dotenv.config();
const app = express();
const port = process.env.PORT || 3008;

// Check if SSL files exist
// const sslKeyPath = '/home/demoservice2/public_html/jcnuplyn-bot/ssl/service2.key';
// const sslCertPath = '/home/demoservice2/public_html/jcnuplyn-bot/ssl/service2.crt';

const sslKeyPath = '/home/servicedemoweb/public_html/duke-bot/ssl/service2.key';
const sslCertPath = '/home/servicedemoweb/public_html/duke-bot/ssl/service2.crt';

let server;

if (true) {
    
    server = https.createServer({
    //  key: fs.readFileSync('./../../../ssl/keys/key.pem'),
    //  cert: fs.readFileSync('./../../../ssl/certs/crt.pem'),
    
        key: fs.readFileSync(sslKeyPath),
        cert: fs.readFileSync(sslCertPath),
     
    }, app);
    
    console.log('Starting server with HTTPS...');

    // Specify allowed origins
    const allowedOrigins = ['https://service2.demowebsitelinks.com', 'https://service.demowebsitelinks.com','https://dukesexcavation.com', 'http://homestead81.test'];

    app.use(cors({
        origin: allowedOrigins
    }));
} else {
    server = http.createServer(app);
    console.log('Starting server with HTTP...');
    app.use(cors());
}

app.use(express.json());

app.options('*', cors());

server.listen(port, () => {
    console.log(`Server running on https://service.demowebsitelinks.com:${port}`);
});


(async () => {
  const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
  organization: process.env.OPENAI_ORG_ID,
  project: process.env.OPENAI_PROJECT_ID
});


    const fetch = await import('node-fetch');

    // Route to creating new thread
    app.get('/getThread', async (req, res) => {
        const initMsg = process.env.INITIAL_MESSAGE
        try {
            const response = await openai.beta.threads.create();
            response.initMsg = initMsg
            res.json(response);
        } catch (error) {
            console.error(error);
            res.status(500).send('Error creating thread');
        }
    })

    // Route to handle sending messages
    app.post('/sendMessage', async (req, res) => {
        const {message, threadId} = req.body;
        const assistantId = process.env.OPENAI_ASSISTANT_ID;

        try {
            await openai.beta.threads.messages.create(threadId, {
                role: "user",
                content: message
            });

            // Run the Assistant
            let runResponse = await openai.beta.threads.runs.create(threadId, {
                assistant_id: assistantId,
            });

            // Check the Run status
            let run = await openai.beta.threads.runs.retrieve(threadId, runResponse.id);
            while (run.status !== "completed") {
                await new Promise((resolve) => setTimeout(resolve, 1000));
                run = await openai.beta.threads.runs.retrieve(threadId, runResponse.id);
            }

            // Display the Assistant's Response
            const messagesResponse = await openai.beta.threads.messages.list(threadId);
            const assistantResponses = messagesResponse.data.filter(msg => msg.role === 'assistant');
            const response = assistantResponses.map(msg =>
                msg.content
                    .filter(contentItem => contentItem.type === 'text')
                    .map(textContent => textContent.text.value)
                    .join('\n')
            ).join('\n');

            res.json(assistantResponses);
        } catch (error) {
            console.error(error);
            res.status(500).send('Error creating thread');
        }
    });

    // Route to get the thread using thread id

    app.get('/getMessages/:threadId', async (req, res) => {
        const threadId = req.params.threadId;
        try {
            const messagesResponse = await openai.beta.threads.messages.list(threadId);

            const messages = messagesResponse.data.map(msg => {
                const content = msg.content
                    .filter(item => item.type === 'text')
                    .map(item => item.text.value)
                    .join('\n');
                return {
                    role: msg.role,
                    content: content
                };
            }).reverse();

            res.json(messages);
        } catch (error) {
            console.error(error);

            if (error.status === 404) {
                // Thread not found, create a new one
                try {
                    const newThread = await openai.beta.threads.create();
                    return res.status(404).json({
                        error: 'Thread not found, new thread created',
                        newThreadId: newThread.id,
                    });
                } catch (e) {
                    return res.status(500).send('Error creating new thread');
                }
            }

            res.status(500).send('Error fetching messages');
        }
    });
    
    // Route to handle image generation
    app.post('/generateImage', async (req, res) => {
        try {
            const {prompt} = req.body;
            const response = await fetch.default('https://api.openai.com/v1/images/generations', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer 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`
                },
                body: JSON.stringify({
                    model: "dall-e-3",
                    prompt: prompt,
                    n: 1,
                    size: '1024x1024'
                })
            });
            const data = await response.json();
            res.json(data);
        } catch (error) {
            console.error(error);
            res.status(500).send('Error creating thread');
        }
    });

})().catch(err => {
    console.error('Error importing node-fetch:', err);
});
