const actions = {

    prompt: {
        label: 'Prompt',
        icon: 'chat',
        handler(root) {

            VueView.ui.modal('autopilot:assets/dialogs/prompt.js', {
                fields: Object.keys(root.document).filter(field => field[0] !== '_'),
                root: root,
                handler(prompt, messageClb) {

                    if (!prompt.trim()) return;

                    let message = [];

                    const fieldsInPrompt = (prompt.match(/:\w+/g) || []).map(word => word.substring(1));
                    const reference = {};

                    if (fieldsInPrompt.length) {

                        fieldsInPrompt.forEach(field => {
                            if (root.document[field] === undefined) return;
                            reference[field] = root.document[field];
                        });

                        message = message.concat([
                            'CONTEXT: You are working within a Cockpit CMS content management system.',
                            'The following JSON contains field data from the current content item:',
                            JSON.stringify(reference, null, 2),
                            '',
                            'INSTRUCTIONS:',
                            '- You are an expert content creator working within Cockpit CMS',
                            '- Generate high-quality, engaging content that fits the context and purpose',
                            '- Reference field values when relevant to the user\'s request',
                            '- Maintain consistency with existing content tone and style',
                            '- Consider SEO best practices and user engagement when applicable',
                            '- Return only the content without explanations or meta-commentary',
                            ''
                        ]);
                    } else {
                        message = message.concat([
                            'INSTRUCTIONS:',
                            '- You are an expert content creator working within Cockpit CMS',
                            '- Generate high-quality, engaging content that fits the context and purpose',
                            '- Consider SEO best practices and user engagement when applicable',
                            '- Return only the content without explanations or meta-commentary',
                            ''
                        ]);
                    }

                    message = message.concat([
                        'User input:',
                        prompt
                    ]).join("\n");

                    root.execute([{
                        role: 'user',
                        content: message
                    }], (msg) => {
                        messageClb(msg.replace(/^\"|\"$/g, ''));
                        //root.updateValue(msg.replace(/^\"|\"$/g, ''));
                    });
                }
            });

        }
    },

    translate: {
        label: 'Translate',
        handler(root) {

            if (!root.val || !root.val.trim()) {
                return;
            }

            let to = '';

            if (root.field.i18n && root.locale && root.locale !== 'default') {
                to = root.locale;
            }

            App.ui.prompt('Translate to', to, (locale) => {

                if (!locale.trim()) return;

                let message = [
                    'System:',
                    'You are an expert translator with native-level fluency in multiple languages.',
                    'Return only the translated text without any explanations, notes, or additional information.',
                    'Ensure the translation:',
                    '- Preserves the original meaning completely',
                    '- Uses natural phrasing as a native speaker would use',
                    '- Maintains the same tone and style as the original',
                    '- Adapts idioms and expressions appropriately for the target language',
                    '- Considers cultural context and local usage patterns',
                    '',
                    `Target Language: ${locale}`,
                    '',
                    'Text for translation:',
                    root.val
                ].join("\n");

                root.execute([{
                    role: 'user',
                    content: message
                }], (msg) => {
                    root.updateValue(msg);
                });
            });
        }
    },

    shorten: {
        label: 'Shorten',
        handler(root) {

            if (!root.val || !root.val.trim()) {
                return;
            }

            App.ui.prompt('Max length', root.val.length, (maxlength) => {

                if (!maxlength || !(!isNaN(parseFloat(maxlength)) && isFinite(maxlength)) || root.val.length <= maxlength) {
                    return;
                }

                let message = [
                    'Shorten the following text while preserving the core message and key information.',
                    `Target length: maximum ${maxlength} characters.`,
                    'Prioritize clarity and maintain the original tone.',
                    'Remove redundancy but keep essential details.',
                    'Return only the shortened text without explanations.',
                    '',
                    'Original text:',
                    root.val
                ].join("\n");

                root.execute([{
                    role: 'user',
                    content: message
                }], (msg) => {
                    root.updateValue(msg);
                });
            });

        }
    }
}

export default {

    init() {
        return new Promise((resolve, reject) => {
            resolve(actions);
        });
    },
}
