import {
    IExecuteFunctions,
    INodeExecutionData,
    INodeType,
    INodeTypeDescription,
    NodeConnectionType,
} from 'n8n-workflow';

export class MagicDev implements INodeType {
    description: INodeTypeDescription = {
        displayName: '🪄 Magic Dev',
        name: 'magicDev',
        icon: 'fa:gift',
        group: ['transform'],
        version: 5.1,
        subtitle: '={{$parameter["mode"] || "Choose Your Magic"}}',
        description: '🌟 Revolutionary workflow ecosystem: AI Generation, Creator Hub, Quest Unlock & Community Database',
        defaults: { name: '🪄 Magic Dev 5.1' },
        inputs: [NodeConnectionType.Main],
        outputs: [NodeConnectionType.Main],
        properties: [
            {
                displayName: '🪄 Magic Dev 5.1 - Revolutionary Workflow Ecosystem',
                name: 'magicGuide',
                type: 'string',
                typeOptions: { rows: 16, alwaysOpenEditWindow: false },
                default: `🌟 MAGIC DEV 5.1 - Four Revolutionary Features:

🤖 Magic Mapping → A prompt, instance URL, N8N API key, OpenRouter API to teleport your workflow to your instance.

🎁 Creator Mapping → Instance URL, N8N API key and a random creator workflow teleports to your instance.

🔑 Quest Mapping → Instance URL, N8N API key, secret code found in Creator Mapping to win a premium workflow.

🗃️ Magic Market → PUBLISH: Share your workflows with description and public Google Sheets URL | SEARCH: Find workflows by keywords in our community-driven public link database. Help us build one of the largest open source workflow databases in the world!

⭐ FEEDBACK: Optional rating system (1-20 stars) + comments available in all modes

🤝 Creators: Want to collaborate? Contact me via Telegram @magicdev_bot!
💝 Donation: 0xfb1f5190Dd2498Cd25Db95d6b23C7145bc14E667 (multichain)`,
                description: 'Complete Magic Dev guide with clear mapping system'
            },
            {
                displayName: '🎯 Choose Your Magic Mode',
                name: 'mode',
                type: 'options',
                options: [
                    { name: '🤖 Magic Mapping (AI Generation)', value: 'ai_generation' },
                    { name: '🎁 Creator premium Mapping (Community Hub)', value: 'creator_teleport' },
                    { name: '🔑 Quest Mapping (Premium Unlock)', value: 'quest_unlock' },
                    { name: '🗃️ Magic Market (Community Database)', value: 'magic_market' }
                ],
                default: 'ai_generation'
            },
            
            // AI MAGIC MAPPING FIELDS
            {
                displayName: '🌐 N8N Instance URL',
                name: 'aiInstanceUrl',
                type: 'string',
                required: true,
                displayOptions: { show: { mode: ['ai_generation'] } },
                default: '',
                placeholder: 'https://your-n8n-instance.com',
                description: '🌐 Your N8N instance URL for AI workflow teleportation'
            },
            {
                displayName: '🔑 N8N API Key',
                name: 'aiApiKey',
                type: 'string',
                typeOptions: { password: true },
                required: true,
                displayOptions: { show: { mode: ['ai_generation'] } },
                default: '',
                placeholder: 'n8n_api_xxx',
                description: '🔑 Your N8N API key for workflow teleportation'
            },
            {
                displayName: '🤖 OpenRouter API Key',
                name: 'aiOpenrouterKey',
                type: 'string',
                typeOptions: { password: true },
                required: true,
                displayOptions: { show: { mode: ['ai_generation'] } },
                default: '',
                placeholder: 'sk-or-v1-xxx',
                description: '🤖 Your OpenRouter API key for AI generation'
            },
            {
                displayName: '💭 Workflow Prompt',
                name: 'aiPrompt',
                type: 'string',
                typeOptions: { rows: 4 },
                displayOptions: { show: { mode: ['ai_generation'] } },
                default: '',
                placeholder: 'Create an email automation system that processes incoming leads...',
                description: '💭 Describe the workflow you want to generate and teleport'
            },
            {
                displayName: '🎛️ Complexity Level',
                name: 'aiComplexity',
                type: 'options',
                displayOptions: { show: { mode: ['ai_generation'] } },
                options: [
                    { name: '⚡ Simple & Fast', value: 'simple' },
                    { name: '🎯 Balanced & Functional', value: 'balanced' },
                    { name: '🚀 Advanced & Feature-Rich', value: 'advanced' }
                ],
                default: 'balanced',
                description: '🎛️ Choose workflow complexity level for teleportation'
            },

            // CREATOR MAPPING FIELDS
            {
                displayName: '🌐 N8N Instance URL',
                name: 'creatorInstanceUrl',
                type: 'string',
                required: true,
                displayOptions: { show: { mode: ['creator_teleport'] } },
                default: '',
                placeholder: 'https://your-n8n-instance.com',
                description: '🌐 Your N8N instance URL for community workflow teleportation'
            },
            {
                displayName: '🔑 N8N API Key',
                name: 'creatorApiKey',
                type: 'string',
                typeOptions: { password: true },
                required: true,
                displayOptions: { show: { mode: ['creator_teleport'] } },
                default: '',
                placeholder: 'n8n_api_xxx',
                description: '🔑 Your N8N API key for workflow teleportation'
            },
            {
                displayName: '🎯 Category Preference',
                name: 'creatorCategory',
                type: 'options',
                displayOptions: { show: { mode: ['creator_teleport'] } },
                options: [
                    { name: '🎲 Surprise Me (Random)', value: 'random' },
                    { name: '📧 Email & Communication', value: 'email' },
                    { name: '📊 Data & Analytics', value: 'data' },
                    { name: '🔄 Automation & Tasks', value: 'automation' },
                    { name: '🛡️ Security & Monitoring', value: 'security' },
                    { name: '🎨 Creative & Content', value: 'creative' },
                    { name: '🌿 Biomimetic (Golden Ratio)', value: 'biomimetic' }
                ],
                default: 'random',
                description: '🎯 Choose workflow category for teleportation - Special: Biomimetic Golden Ratio workflows!'
            },

            // QUEST MAPPING FIELDS
            {
                displayName: '🌐 N8N Instance URL',
                name: 'questInstanceUrl',
                type: 'string',
                required: true,
                displayOptions: { show: { mode: ['quest_unlock'] } },
                default: '',
                placeholder: 'https://your-n8n-instance.com',
                description: '🌐 Your N8N instance URL for premium workflow teleportation'
            },
            {
                displayName: '🔑 N8N API Key',
                name: 'questApiKey',
                type: 'string',
                typeOptions: { password: true },
                required: true,
                displayOptions: { show: { mode: ['quest_unlock'] } },
                default: '',
                placeholder: 'n8n_api_xxx',
                description: '🔑 Your N8N API key for premium workflow teleportation'
            },
            {
                displayName: '🎫 Quest Secret Code',
                name: 'questCode',
                type: 'string',
                required: true,
                displayOptions: { show: { mode: ['quest_unlock'] } },
                default: '',
                placeholder: 'GOLDEN_RATIO_2025, BTP_BIOMIMETIC_PRO...',
                description: '🎫 Enter your secret quest code found in Creator Mapping workflows!'
            },
            {
                displayName: '📍 Code Source',
                name: 'questSource',
                type: 'options',
                displayOptions: { show: { mode: ['quest_unlock'] } },
                options: [
                    { name: '📱 Telegram Community', value: 'telegram' },
                    { name: '🎮 Discord Server', value: 'discord' },
                    { name: '📧 Newsletter', value: 'newsletter' },
                    { name: '🎉 Special Event', value: 'event' },
                    { name: '🌿 Creator Mapping Workflows', value: 'creator_notes' },
                    { name: '🔍 Hidden URL Discovery', value: 'hidden_url' },
                    { name: '❓ Other Source', value: 'other' }
                ],
                default: 'creator_notes',
                description: '📍 Where did you discover this quest code?'
            },

            // MAGIC MARKET FIELDS
            {
                displayName: '🗃️ Magic Market Action',
                name: 'marketAction',
                type: 'options',
                displayOptions: { show: { mode: ['magic_market'] } },
                options: [
                    { name: '📤 PUBLISH Workflow', value: 'post' },
                    { name: '🔍 SEARCH Workflows', value: 'search' }
                ],
                default: 'post',
                description: '🎯 Choose your Magic Market action'
            },
            {
                displayName: '🔗 Google Sheets URL (Public)',
                name: 'marketPostGoogleSheetUrl',
                type: 'string',
                required: true,
                displayOptions: { show: { mode: ['magic_market'], marketAction: ['post'] } },
                default: '',
                placeholder: 'https://docs.google.com/spreadsheets/d/xxx/edit?usp=sharing',
                description: '🌐 REQUIRED: Public Google Sheets URL containing your workflow'
            },
            {
                displayName: '📝 Workflow Description',
                name: 'marketPostDescription',
                type: 'string',
                typeOptions: { rows: 6 },
                required: true,
                displayOptions: { show: { mode: ['magic_market'], marketAction: ['post'] } },
                default: '',
                placeholder: 'Using the Google Sheet link, our agent will analyze your workflow and create a detailed description to feed our workflow database. Simply provide your creator name and crypto wallet for possible donations....',
                description: '💭 REQUIRED: Detailed workflow description'
            },
            {
                displayName: '🔍 Search Keywords',
                name: 'marketResearchKeywords',
                type: 'string',
                required: true,
                displayOptions: { show: { mode: ['magic_market'], marketAction: ['search'] } },
                default: '',
                placeholder: 'email automation, golden ratio, webhook...',
                description: '🎯 REQUIRED: Keywords to search workflows'
            },
            {
                displayName: '🏷️ Category Filter',
                name: 'marketResearchCategory',
                type: 'options',
                displayOptions: { show: { mode: ['magic_market'], marketAction: ['search'] } },
                options: [
                    { name: '🌟 All Categories', value: 'all' },
                    { name: '📧 Email & Communication', value: 'email' },
                    { name: '📊 Data & Analytics', value: 'data' },
                    { name: '🔄 Automation & Tasks', value: 'automation' },
                    { name: '🛡️ Security & Monitoring', value: 'security' },
                    { name: '🎨 Creative & Content', value: 'creative' },
                    { name: '🌿 Biomimetic (Golden Ratio)', value: 'biomimetic' }
                ],
                default: 'all',
                description: '🏷️ Filter search results by category'
            },
            {
                displayName: '⭐ Minimum Rating',
                name: 'marketResearchMinRating',
                type: 'number',
                displayOptions: { show: { mode: ['magic_market'], marketAction: ['search'] } },
                default: 15,
                typeOptions: { minValue: 1, maxValue: 20 },
                description: '⭐ Minimum quality rating (1-20 scale)'
            },

            // FEEDBACK SYSTEM (ÉTOILES 1-20)
            {
                displayName: '⭐ Rate Your Experience (Optional)',
                name: 'userRating',
                type: 'options',
                options: [
                    { name: '⭐ 1 - Poor', value: 1 },
                    { name: '⭐ 2 - Below Average', value: 2 },
                    { name: '⭐ 3 - Fair', value: 3 },
                    { name: '⭐ 4 - Good', value: 4 },
                    { name: '⭐ 5 - Very Good', value: 5 },
                    { name: '⭐ 6 - Above Average', value: 6 },
                    { name: '⭐ 7 - Great', value: 7 },
                    { name: '⭐ 8 - Very Great', value: 8 },
                    { name: '⭐ 9 - Excellent', value: 9 },
                    { name: '⭐ 10 - Outstanding', value: 10 },
                    { name: '⭐ 11 - Superb', value: 11 },
                    { name: '⭐ 12 - Magnificent', value: 12 },
                    { name: '⭐ 13 - Exceptional', value: 13 },
                    { name: '⭐ 14 - Extraordinary', value: 14 },
                    { name: '⭐ 15 - Phenomenal', value: 15 },
                    { name: '⭐ 16 - Incredible', value: 16 },
                    { name: '⭐ 17 - Amazing', value: 17 },
                    { name: '⭐ 18 - Spectacular', value: 18 },
                    { name: '⭐ 19 - Perfect', value: 19 },
                    { name: '⭐ 20 - Magic!', value: 20 }
                ],
                default: 10,
                description: '📊 Rate your Magic Dev experience (1-20 scale)'
            },
            {
                displayName: '💭 Your Comments (Optional)',
                name: 'userComments',
                type: 'string',
                typeOptions: { rows: 3 },
                default: '',
                placeholder: 'Share your thoughts about Magic Dev...',
                description: '💭 Share your feedback'
            }
        ]
    };

    async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
        const items = this.getInputData();
        const returnData: INodeExecutionData[] = [];
        
        for (let i = 0; i < items.length; i++) {
            try {
                const mode = this.getNodeParameter('mode', i, 'ai_generation') as string;
                let payload: any = {
                    mode,
                    timestamp: new Date().toISOString()
                };

                // RÉCUPÉRATION DU FEEDBACK (TRANSMIS À TON AGENT)
                const userRating = this.getNodeParameter('userRating', i, null);
                const userComments = this.getNodeParameter('userComments', i, '');
                
                if (userRating !== null) {
                    payload.feedback = {
                        rating: userRating,
                        comments: (userComments || '').toString().trim(),

                        mode: mode,
                        timestamp: new Date().toISOString()
                    };
                }

                // TRAITEMENT PAR MODE
                if (mode === 'ai_generation') {
                    payload.aiInstanceUrl = this.getNodeParameter('aiInstanceUrl', i, '') as string;
                    payload.aiApiKey = this.getNodeParameter('aiApiKey', i, '') as string;
                    payload.aiOpenrouterKey = this.getNodeParameter('aiOpenrouterKey', i, '') as string;
                    payload.aiPrompt = this.getNodeParameter('aiPrompt', i, '') as string;
                    payload.aiComplexity = this.getNodeParameter('aiComplexity', i, 'balanced') as string;
                    
                    if (!payload.aiInstanceUrl || !payload.aiApiKey || !payload.aiOpenrouterKey) {
                        throw new Error('AI Instance URL, AI API Key, and OpenRouter Key are required');
                    }
                } else if (mode === 'creator_teleport') {
                    payload.creatorInstanceUrl = this.getNodeParameter('creatorInstanceUrl', i, '') as string;
                    payload.creatorApiKey = this.getNodeParameter('creatorApiKey', i, '') as string;
                    payload.creatorCategory = this.getNodeParameter('creatorCategory', i, 'random') as string;
                    
                    if (!payload.creatorInstanceUrl || !payload.creatorApiKey) {
                        throw new Error('Creator Instance URL and Creator API Key are required');
                    }
                } else if (mode === 'quest_unlock') {
                    payload.questInstanceUrl = this.getNodeParameter('questInstanceUrl', i, '') as string;
                    payload.questApiKey = this.getNodeParameter('questApiKey', i, '') as string;
                    payload.questCode = this.getNodeParameter('questCode', i, '') as string;
                    payload.questSource = this.getNodeParameter('questSource', i, 'creator_notes') as string;
                    
                    if (!payload.questInstanceUrl || !payload.questApiKey || !payload.questCode) {
                        throw new Error('Quest Instance URL, Quest API Key, and Quest Code are required');
                    }
                } else if (mode === 'magic_market') {
                    const marketAction = this.getNodeParameter('marketAction', i, 'post') as string;
                    payload.marketAction = marketAction;
                    
                    if (marketAction === 'post') {
                        payload.marketPostGoogleSheetUrl = this.getNodeParameter('marketPostGoogleSheetUrl', i, '') as string;
                        payload.marketPostDescription = this.getNodeParameter('marketPostDescription', i, '') as string;
                        
                        if (!payload.marketPostGoogleSheetUrl || !payload.marketPostDescription) {
                            throw new Error('Google Sheet URL and Description are required for posting');
                        }
                    } else if (marketAction === 'search') {
                        payload.marketResearchKeywords = this.getNodeParameter('marketResearchKeywords', i, '') as string;
                        payload.marketResearchCategory = this.getNodeParameter('marketResearchCategory', i, 'all') as string;
                        payload.marketResearchMinRating = this.getNodeParameter('marketResearchMinRating', i, 15) as number;
                        
                        if (!payload.marketResearchKeywords) {
                            throw new Error('Search keywords are required');
                        }
                    }
                }

                // APPEL WEBHOOK - RETOUR 100% PUR DE TON AGENT
                const response = await this.helpers.request({
                    method: 'POST',
                    url: 'https://n8n.srv740722.hstgr.cloud/webhook/magique_dev',
                    body: payload,
                    headers: { 'Content-Type': 'application/json' }
                });

                // RETOUR DIRECT SANS AUCUN FEEDBACK AUTOMATIQUE
                returnData.push({
                    json: response,
                    pairedItem: { item: i }
                });
                
            } catch (error) {
                // ERREUR SIMPLE SANS POLLUTION
                const errorMessage = error instanceof Error ? error.message : 'Unknown error';
                returnData.push({
                    json: { 
                        error: errorMessage
                    },
                    pairedItem: { item: i }
                });
            }
        }
        
        return [returnData];
    }
}

