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

export class MagicDev implements INodeType {
    description: INodeTypeDescription = {
        displayName: '🪄 Magic Dev',
        name: 'magicDev',
        icon: 'data:image/svg+xml;utf8,<svg width="60" height="60" xmlns="http://www.w3.org/2000/svg"><rect x="15" y="20" width="30" height="25" fill="%23dc2626" rx="3"/><rect x="28" y="20" width="4" height="25" fill="%23fca5a5"/><rect x="15" y="30" width="30" height="4" fill="%23fca5a5"/><ellipse cx="30" cy="18" rx="8" ry="4" fill="%23dc2626"/></svg>' as any,



        group: ['transform'],
        version: 5.0,
        subtitle: '={{$parameter["mode"] || "Choose Your Magic"}}',
        description: '🌟 Revolutionary workflow ecosystem: AI Generation, Creator Hub, Quest Unlock & Community Database',
        defaults: { name: '🪄 Magic Dev 5.0' },
        inputs: [NodeConnectionType.Main],
        outputs: [NodeConnectionType.Main],
        properties: [
            {
                displayName: '🪄 Magic Dev 5.0 - Revolutionary Update',
                name: 'magicGuide',
                type: 'string',
                typeOptions: { rows: 12, alwaysOpenEditWindow: false },
                default: `🌟 MAGIC DEV 5.0 - Four Revolutionary Features:

🤖 AI Magic Generator → Generate workflows with AI prompts + OpenRouter key
🎁 Creator Magic Hub → Access curated community workflows (includes 🌿 biomimetic category!)
🔑 Quest Magic Unlock → Unlock premium biomimetic BTP workflows with secret codes
🗃️ Magic Market → Post/search workflows in collaborative database (NEW!)

🌿 BIOMIMETIC PIONEER: Submit Golden Ratio workflows to become a recognized pioneer!
💰 CRYPTO DONATIONS: Include your wallet in workflow descriptions for community support
🎮 QUEST SYSTEM: Find secret codes hidden in creator workflows to unlock premium content

🤝 Creators: Contact via Telegram for collaboration
💝 Donation: 0xfb1f5190Dd2498Cd25Db95d6b23C7145bc14E667 (multichain)
🤖 Community: https://t.me/magicdev_bot`,
                description: 'Complete Magic Dev 5.0 guide with all new features'
            },
            {
                displayName: '🎯 Choose Your Magic Mode',
                name: 'mode',
                type: 'options',
                options: [
                    { name: '🤖 AI Magic Generator', value: 'ai_generation', description: 'Generate workflows with AI - OpenRouter key required' },
                    { name: '🎁 Creator Magic Hub', value: 'creator_teleport', description: 'Access curated community workflows' },
                    { name: '🔑 Quest Magic Unlock', value: 'quest_unlock', description: 'Unlock premium biomimetic workflows' },
                    { name: '🗃️ Magic Market', value: 'magic_market', description: 'Post or search community workflows (NEW!)' }
                ],
                default: 'ai_generation',
                description: '🪄 Revolutionary 4-in-1 Magic System!'
            },
            
            // AI MODE FIELDS
            {
                displayName: 'AI 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-generated workflows'
            },
            {
                displayName: 'AI 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'
            },
            {
                displayName: 'AI OpenRouter 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 (you pay only what you use!)'
            },
            {
                displayName: 'AI 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 create'
            },
            {
                displayName: 'AI 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'
            },

            // CREATOR MODE FIELDS  
            {
                displayName: 'Creator 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 workflows'
            },
            {
                displayName: 'Creator 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'
            },
            {
                displayName: 'Creator 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 - NEW: Biomimetic Golden Ratio workflows!'
            },

            // QUEST MODE FIELDS
            {
                displayName: 'Quest 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 quest workflows'
            },
            {
                displayName: 'Quest 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'
            },
            {
                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 (find them in creator workflows!)'
            },
            {
                displayName: 'Quest 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 Workflow Notes', 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 MODE FIELDS (NEW!)
            {
                displayName: '🗃️ Magic Market Action',
                name: 'marketAction',
                type: 'options',
                displayOptions: { show: { mode: ['magic_market'] } },
                options: [
                    { name: '📤 Post Workflow', value: 'post', description: 'Share your workflow with the community' },
                    { name: '🔍 Search Workflows', value: 'search', description: 'Find workflows by keywords' }
                ],
                default: 'post',
                description: '🎯 Choose your Magic Market action'
            },
            {
                displayName: '🔗 Google Sheet URL',
                name: 'marketPostGoogleSheetUrl',
                type: 'string',
                required: true,
                displayOptions: { show: { mode: ['magic_market'], marketAction: ['post'] } },
                default: '',
                placeholder: 'https://docs.google.com/spreadsheets/d/xxx',
                description: '🌐 URL of your Google Sheet containing the workflow'
            },
            {
                displayName: '📝 Workflow Description',
                name: 'marketPostDescription',
                type: 'string',
                typeOptions: { rows: 6 },
                required: true,
                displayOptions: { show: { mode: ['magic_market'], marketAction: ['post'] } },
                default: '',
                placeholder: `Describe your workflow, its features, technologies...

You can also include:
• Your crypto wallet for donations: 0x1234...abcd  
• Keywords: Golden Ratio, biomimetic, fibonacci, email automation
• Contact info, special features, etc.

Everything in this description will be intelligently processed by our AI agent!`,
                description: '💭 Free-form description - include everything relevant!'
            },
            {
                displayName: '🔍 Search Keywords', 
                name: 'marketResearchKeywords',
                type: 'string',
                required: true,
                displayOptions: { show: { mode: ['magic_market'], marketAction: ['search'] } },
                default: '',
                placeholder: 'email automation, golden ratio, webhook, CRM...',
                description: '🎯 Keywords to search for 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 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)'
            }
        ]
    };

    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(),
                    version: '5.0.0'
                };

                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');
                        }
                    }
                }

                const webhookUrl = 'https://n8n.srv740722.hstgr.cloud/webhook/magique_dev';

                const response = await this.helpers.request({
                    method: 'POST',
                    url: webhookUrl,
                    body: payload,
                    headers: { 'Content-Type': 'application/json' }
                });

                let successMessage = '🎉 Magic Dev 5.0 completed successfully!';
                if (mode === 'creator_teleport') {
                    successMessage = '🎁 Creator workflow magically deployed!';
                } else if (mode === 'ai_generation') {
                    successMessage = '🤖 AI workflow magically generated and deployed!';
                } else if (mode === 'quest_unlock') {
                    successMessage = '🔑 Quest workflow magically unlocked and deployed!';
                } else if (mode === 'magic_market') {
                    const action = payload.marketAction;
                    successMessage = action === 'post' ? 
                        '📤 Workflow posted to Magic Market!' : 
                        '🔍 Magic Market search completed!';
                }

                returnData.push({
                    json: {
                        success: true,
                        mode,
                        version: '5.0.0',
                        message: response.message || successMessage,
                        result: response.result,
                        magicTip: '💡 Check your N8N workflows or Magic Market for results!',
                        newFeatures: '🌟 Magic Dev 5.0: Now with Community Database & Biomimetic Workflows!',
                        donation: '💝 Magic Dev: 0xfb1f5190Dd2498Cd25Db95d6b23C7145bc14E667'
                    },
                    pairedItem: { item: i }
                });
                
            } catch (error) {
                const errorMessage = error instanceof Error ? error.message : 'Unknown magical error';
                returnData.push({
                    json: {
                        success: false,
                        error: errorMessage,
                        version: '5.0.0',
                        magicHelp: '🆘 Need help? Join: https://t.me/magicdev_bot',
                        donation: '💝 Magic Dev: 0xfb1f5190Dd2498Cd25Db95d6b23C7145bc14E667'
                    },
                    pairedItem: { item: i }
                });
            }
        }
        
        return [returnData];
    }
}
