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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
import gradio as gr
import base64
import asyncio
import json
import os
from mcp import ClientSession, StdioServerParameters, types
from mcp.client.stdio import stdio_client
from typing import List
import nest_asyncio
import threading
import queue
import time
from PIL import Image
from io import BytesIO
os.makedirs("ContentCreator/created_image", exist_ok=True)

nest_asyncio.apply()


class MCP_Modal_Marketing_Tool:
    def __init__(self):
        self.session: ClientSession = None
        self.available_tools: List[dict] = []
        self.is_connected = False
        self.request_queue = queue.Queue()
        self.result_queue = queue.Queue()

    async def call_mcp_tool(self, tool_name: str, arguments: dict):
        """Generic method to call any MCP tool"""
        try:
            result = await self.session.call_tool(tool_name, arguments=arguments)
            if hasattr(result, 'content') and result.content:
                return result.content[0].text
            return None
        except Exception as e:
            print(f"Error calling tool {tool_name}: {str(e)}")
            raise e

    async def process_queue(self):
        """Process requests from the queue"""
        while True:
            try:
                if not self.request_queue.empty():
                    item = self.request_queue.get()
                    if item == "STOP":
                        break

                    tool_name, arguments, request_id = item
                    try:
                        result = await self.call_mcp_tool(tool_name, arguments)
                        self.result_queue.put(("success", result, request_id))
                    except Exception as e:
                        self.result_queue.put(("error", str(e), request_id))
                else:
                    await asyncio.sleep(0.1)
            except Exception as e:
                print(f"Error in process_queue: {str(e)}")

    async def connect_to_server_and_run(self):
        """Connect to MCP server and start processing"""
        server_params = StdioServerParameters(
            command="python",
            args=["mcp_server.py"],
            env=None,
        )

        async with stdio_client(server_params) as (read, write):
            async with ClientSession(read, write) as session:
                self.session = session
                await session.initialize()

                response = await session.list_tools()
                tools = response.tools
                print("Connected to MCP server with tools:",
                      [tool.name for tool in tools])

                self.available_tools = [{
                    "name": tool.name,
                    "description": tool.description,
                    "input_schema": tool.inputSchema
                } for tool in tools]

                self.is_connected = True
                print("Marketing Tool MCP Server connected!")

                # Check Modal health
                health_result = await self.call_mcp_tool("health_check", {})
                print(f"Modal API Status: {health_result}")

                await self.process_queue()


# Global instance
marketing_tool = MCP_Modal_Marketing_Tool()


def wait_for_result(request_id, timeout=300):
    """Wait for a result with a specific request ID"""
    start_time = time.time()
    while time.time() - start_time < timeout:
        if not marketing_tool.result_queue.empty():
            status, result, result_id = marketing_tool.result_queue.get()
            if result_id == request_id:
                return status, result
            else:
                # Put it back if it's not our result
                marketing_tool.result_queue.put((status, result, result_id))
        time.sleep(0.1)
    return "error", "Timeout"


def decode_and_save_image(image_b64, filename):
    """Decode base64 and save image"""
    import base64
    from PIL import Image
    from io import BytesIO

    # Ensure the path is inside created_image/
    full_path = os.path.join("ContentCreator/created_image", filename)
    image_b64 = image_b64.strip()
    missing_padding = len(image_b64) % 4
    if missing_padding:
        image_b64 += '=' * (4 - missing_padding)

    image_data = base64.b64decode(image_b64)
    image = Image.open(BytesIO(image_data))
    image.save(full_path)
    return full_path


def single_image_generation(prompt, num_steps, style):
    """Generate a single image with optional style"""
    if not marketing_tool.is_connected:
        return None, "⚠️ MCP Server not connected. Please wait a few seconds and try again."

    try:
        request_id = f"single_{time.time()}"

        # Apply style if selected
        if style != "none":
            style_request_id = f"style_{time.time()}"
            marketing_tool.request_queue.put((
                "add_style_modifier",
                {"prompt": prompt, "style": style},
                style_request_id
            ))

            status, result = wait_for_result(style_request_id, timeout=50)
            if status == "success":
                style_data = json.loads(result)
                prompt = style_data["enhanced_prompt"]

        # Generate image
        marketing_tool.request_queue.put((
            "generate_and_save_image",
            {"prompt": prompt, "num_inference_steps": num_steps},
            request_id
        ))

        status, result = wait_for_result(request_id)

        if status == "success":
            filename = decode_and_save_image(
                result, f"generated_{int(time.time())}.png")
            return filename, f"βœ… Image generated successfully!\nπŸ“ Final prompt: {prompt}"
        else:
            return None, f"❌ Error: {result}"

    except Exception as e:
        return None, f"❌ Error: {str(e)}"


# Update the batch generation function in app.py
def enhanced_batch_generation(prompt, variation_type, count, num_steps):
    """Generate strategic variations for A/B testing"""
    if not marketing_tool.is_connected:
        return None, "⚠️ MCP Server not connected. Please wait a few seconds and try again."
        
    try:
        request_id = f"smart_batch_{time.time()}"
        marketing_tool.request_queue.put((
            "batch_generate_smart_variations",
            {
                "prompt": prompt, 
                "count": count, 
                "variation_type": variation_type,
                "num_inference_steps": num_steps
            },
            request_id
        ))
        
        status, result = wait_for_result(request_id, timeout=300)  # Longer timeout for batch
        
        if status == "success":
            batch_data = json.loads(result)
            images = []
            variation_details = []
            
            for i, img_data in enumerate(batch_data["images"]):
                filename = decode_and_save_image(
                    img_data["image_base64"], 
                    f"variation_{i+1}_{int(time.time())}.png"
                )
                images.append(filename)
                
                variation_details.append(
                    f"**Variation {i+1}:** {img_data['variation_description']}\n"
                    f"*Testing Purpose:* {img_data['testing_purpose']}\n"
                )
            
            strategy_explanation = batch_data.get("testing_strategy", "")
            
            status_message = (
                f"βœ… Generated {len(images)} strategic variations!\n\n"
                f"**Testing Strategy:** {strategy_explanation}\n\n"
                f"**Variations Created:**\n" + 
                "\n".join(variation_details) +
                f"\nπŸ’‘ **Next Steps:** Post each variation and track engagement metrics to see which performs best!"
            )
            
            return images, status_message
        else:
            return None, f"❌ Error: {result}"
            
    except Exception as e:
        return None, f"❌ Error: {str(e)}"

# Update the strategy info based on selection
def update_strategy_info(variation_type):
    strategy_descriptions = {
        "mixed": {
            "title": "Mixed Strategy Testing",
            "description": "Tests multiple variables (colors, layout, mood) to find overall best approach",
            "use_case": "Best for comprehensive optimization when you're not sure what to test first"
        },
        "color_schemes": {
            "title": "Color Psychology Testing", 
            "description": "Tests how different color schemes affect emotional response and engagement",
            "use_case": "Great for brand content, product launches, and emotional marketing"
        },
        "composition_styles": {
            "title": "Layout & Composition Testing",
            "description": "Tests different visual arrangements and focal points",
            "use_case": "Perfect for optimizing visual hierarchy and user attention flow"
        },
        "emotional_tones": {
            "title": "Emotional Tone Testing",
            "description": "Tests different moods and feelings to see what resonates with your audience", 
            "use_case": "Ideal for brand personality and audience connection optimization"
        },
        "social_media": {
            "title": "Platform Optimization Testing",
            "description": "Tests platform-specific elements and styles",
            "use_case": "Essential for multi-platform content strategies"
        },
        "engagement_hooks": {
            "title": "Attention-Grabbing Testing",
            "description": "Tests different ways to capture and hold viewer attention",
            "use_case": "Critical for improving reach and stopping scroll behavior"
        },
        "brand_positioning": {
            "title": "Brand Positioning Testing", 
            "description": "Tests how different brand personalities affect audience perception",
            "use_case": "Important for brand development and target audience alignment"
        }
    }
    
    info = strategy_descriptions.get(variation_type, strategy_descriptions["mixed"])
    return f"""
    **πŸ’‘ Current Strategy:** {info['title']}
    
    **What this tests:** {info['description']}
    
    **Best for:** {info['use_case']}
    """

def social_media_generation(prompt, platforms, num_steps):
    """Generate images for multiple social media platforms with correct resolutions"""
    if not marketing_tool.is_connected:
        return None, "MCP Server not connected"
        
    try:
        request_id = f"social_{time.time()}"
        marketing_tool.request_queue.put((
            "generate_social_media_set",
            {"prompt": prompt, "platforms": platforms, "num_inference_steps": num_steps},
            request_id
        ))
        
        status, result = wait_for_result(request_id)
        
        if status == "success":
            social_data = json.loads(result)
            results = []
            
            for platform_data in social_data["results"]:
                filename = decode_and_save_image(
                    platform_data["image_base64"],
                    f"{platform_data['platform']}_{platform_data['resolution']}_{int(time.time())}.png"
                )
                results.append((platform_data["platform"], filename, platform_data["resolution"]))
                
            # Create a status message with resolutions
            if results:
                status_msg = "Generated images:\n" + "\n".join([
                    f"β€’ {r[0]}: {r[2]}" for r in results
                ])
                return [r[1] for r in results], status_msg
            else:
                return None, "No images generated"
        else:
            return None, f"Error: {result}"
            
    except Exception as e:
        return None, f"Error: {str(e)}"


def start_mcp_server():
    """Start MCP server in background"""
    def run_server():
        asyncio.run(marketing_tool.connect_to_server_and_run())

    thread = threading.Thread(target=run_server, daemon=True)
    thread.start()
    return thread


# Platform size presets for reference
SIZE_PRESETS = {
    "instagram_post": (1080, 1080),
    "instagram_story": (1080, 1920),
    "twitter_post": (1200, 675),
    "linkedin_post": (1200, 1200),
    "facebook_cover": (1200, 630),
    "youtube_thumbnail": (1280, 720)
}

# Create Gradio interface with tabs
with gr.Blocks(title="AI Marketing Content Generator") as demo:
    gr.Markdown("""
    # 🎨 AI Marketing Content Generator
    ### Powered by Flux AI on Modal GPU via MCP
    
    Generate professional marketing images with AI - optimized for content creators and marketers!
    
    ⏰ **Please wait 5-10 seconds after launching for the MCP server to connect**
    """)

    # Connection status
    connection_status = gr.Markdown("πŸ”„ Connecting to MCP server...")

    with gr.Tabs():
        # Instructions Tab (First)
        # Instructions Tab (First)
        with gr.TabItem("πŸ“– Quick Start"):
            gr.Markdown("""
            ## πŸš€ Get Started in 3 Steps
            
            1. **Wait for Connection** βœ… (Status shown above)
            2. **Pick a Tab** β†’ Choose what you need to create
            3. **Generate** β†’ Enter details and click generate
            
            ### 🎯 What Each Tab Does:
            - **πŸ–ΌοΈ Single Image**: Create one professional marketing image
            - **πŸ”„ A/B Testing**: Generate variations to test what works best  
            - **πŸ“± Social Media**: Create multiple platform-sized images at once
            - **πŸ€– AI Assistant**: Let AI write the perfect prompt for you
            """)
            
            with gr.Accordion("πŸ“š Detailed Guide & Tips", open=False):
                gr.Markdown("""
            ## Welcome to AI Marketing Content Generator! 
            
            This tool helps you create professional marketing images using AI. Here's how to use each feature:
            
            ### πŸš€ Quick Start Guide
            
            1. **Wait for Connection**: The status above should show "βœ… Connected" before you start
            2. **Choose Your Task**: Select a tab based on what you need
            3. **Enter Details**: Fill in the prompts and settings
            4. **Generate**: Click the generate button and wait for results
            
            ### πŸ“‘ Feature Overview
            
            #### 1️⃣ Single Image Tab
            - **Best for**: Individual marketing assets, blog headers, social posts
            - **How to use**:
                1. Enter a descriptive prompt
                2. Choose a style preset (optional)
                3. Adjust quality with steps (higher = better but slower)
                4. Click Generate
            
            #### 2️⃣ A/B Testing Batch Tab  
            - **Best for**: Creating variations to test engagement
            - **How to use**:
                1. Enter your base prompt
                2. Select how many variations (2-5)
                3. Generate and compare results
            
            #### 3️⃣ Social Media Pack Tab
            - **Best for**: Multi-platform campaigns
            - **How to use**:
                1. Enter your content prompt
                2. Check the platforms you need
                3. Generate all sizes at once
            
            #### 4️⃣ Prompt Templates Tab
            - **Best for**: Quick professional prompts
            - **How to use**:
                1. Select a template type
                2. Fill in the required variables
                3. Apply template
                4. Use the generated prompt
            
            ### πŸ’‘ Pro Tips
            
            - **Be Specific**: "Product photo of red shoes on white background" > "shoes"
            - **Use Styles**: Apply style presets for consistent branding
            - **Higher Steps**: Use 70-100 steps for final production images
            - **Test First**: Use lower steps (30-40) for quick tests
            - **Save Prompts**: Keep successful prompts for future use
            
            ### 🎯 Common Use Cases
            
            1. **E-commerce Product Photos**
               ```
               Prompt: "Professional product photography of [product], white background, studio lighting"
               Style: professional
               Steps: 70
               ```
            
            2. **Social Media Announcements**
               ```
               Prompt: "Eye-catching announcement graphic for [event/sale], bold colors"
               Style: playful
               Steps: 50
               ```
            
            3. **Blog Headers**
               ```
               Prompt: "Minimalist header image about [topic], modern design"
               Style: minimalist
               Steps: 50
               ```
            
            ### ⚠️ Troubleshooting
            
            - **"Not Connected" Error**: Wait 10 seconds and refresh the page
            - **Timeout Errors**: The GPU might be cold starting, try again
            - **Poor Quality**: Increase steps to 70+ for better results
            - **Wrong Style**: Make sure to select style before generating
            """)

        # Single Image Generation Tab
        with gr.TabItem("πŸ–ΌοΈ Single Image"):
            with gr.Row():
                with gr.Column():
                    single_prompt = gr.Textbox(
                        label="Prompt",
                        placeholder="Describe your image in detail...\nExample: Professional headshot of business person in modern office",
                        lines=3
                    )
                    with gr.Row():
                        single_style = gr.Dropdown(
                            choices=["none", "professional", "playful",
                                     "minimalist", "luxury", "tech"],
                            value="none",
                            label="Style Preset",
                            info="Apply a consistent style to your image"
                        )
                        single_steps = gr.Slider(
                            10, 100, 50,
                            step=10,
                            label="Quality (Inference Steps)",
                            info="Higher = better quality but slower"
                        )
                    single_btn = gr.Button(
                        "🎨 Generate Image", variant="primary", size="lg")

                    # Quick examples
                    with gr.Accordion("πŸ’­ Example Ideas",open=False):
                        gr.Examples(
                            examples=[
                                ["""This poster is dominated by blue-purple neon lights, with the background of a hyper city at night, with towering skyscrapers surrounded by colorful LED light strips. In the center of the picture is a young steampunk modern robot with virtual information interfaces and digital codes floating around him. The future fonted title "CYNAPTICS" is in neon blue, glowing, as if outlined by laser, exuding a sense of technology and a cold and mysterious atmosphere. The small words "FUTURE IS NOW" seem to be calling the audience to the future, full of science fiction and trendy charm""", "professional", 50],
                                ["poster of,a white girl,A young korean woman pose with a white Vespa scooter on a sunny day,dressed in a stylish red and white jacket .inside a jacket is strapless,with a casual denim skirt. She wears a helmet with vintage-style goggles,and converse sneakers,adding a retro touch to her outfit. The bright sunlight highlights her relaxed and cheerful expression,and the VespaҀ™s white color pops against the clear blue sky. The background features a vibrant,sunlit scene with a few trees or distant buildings,creating a fresh and joyful atmosphere. Art style: realistic,high detail,vibrant colors,warm and cheerful.,f1.4 50mm,commercial photo style,with text around is 'Chasing the sun on my Vespa nothing but the open road ahead'", "playful", 40],
                                ["""Badminton is not just about winning, it’s about daring to challenge the limits of speed and precision. It’s a game where every strike is a test of reflexes, every point a moment of courage. To play badminton is to engage in a battle of endurance, strategy, and passion.""", "minimalist", 50],
                                ],
                            inputs=[single_prompt, single_style, single_steps],
                            label="Quick Examples"
                            )

                with gr.Column():
                    single_output = gr.Image(
                        label="Generated Image", type="filepath")
                    single_status = gr.Textbox(
                        label="Status", lines=3, interactive=False)

        # Batch Generation Tab
        with gr.TabItem("πŸ”„ A/B Testing Batch"):
            gr.Markdown("""
                        ### Generate Strategic Variations for Testing
                        Create different versions that test specific elements to optimize your content performance.
                        Each variation tests a different hypothesis about what works best for your audience.
                        """)
            with gr.Row():
                with gr.Column():
                    batch_prompt = gr.Textbox(
                        label="Base Content Prompt",
                        placeholder="Describe your core content idea...\nExample: Professional announcement for new product launch",
                        lines=3
                    )
                    batch_variation_type = gr.Dropdown(
                        choices=[
                            ("🎨 Mixed Strategy (Recommended)", "mixed"),
                            ("🌈 Color Psychology Test", "color_schemes"),
                            ("πŸ“ Layout & Composition Test", "composition_styles"),
                            ("😊 Emotional Tone Test", "emotional_tones"),
                            ("πŸ“± Platform Optimization Test", "social_media"),
                            ("πŸ‘οΈ Attention-Grabbing Test", "engagement_hooks"),
                            ("🏷️ Brand Positioning Test", "brand_positioning")
                            ],
                        value="mixed",
                        label="Testing Strategy",
                        info="Choose what aspect you want to test"
                        )
                    with gr.Row():
                        batch_count = gr.Slider(
                            2, 5, 3,
                            step=1,
                            label="Number of Variations",
                            info="How many different versions to generate"
                            )
                        batch_steps = gr.Slider(
                            10, 100, 40,
                            label="Quality (Inference Steps)",info="Lower steps for quick testing")

                    batch_btn = gr.Button(
                        "πŸ”„ Generate Variations", variant="primary", size="lg")
                    
                    strategy_info = gr.Markdown("""
                                                **πŸ’‘ Current Strategy:** Mixed approach testing multiple variables
                                                **What this tests:** Different colors, layouts, and styles to find what works best
                                                **How to use results:** Post each variation and compare engagement metrics
                                                """)


                with gr.Column():
                    batch_output = gr.Gallery(
                        label="Generated Test Variations",
                        columns=2,
                        height="auto"
                    )
                    batch_status = gr.Textbox(
                        label="Variation Details", lines=6, interactive=False)
                    with gr.Accordion("πŸ“Š A/B Testing Guide",open=False):
                        gr.Markdown("""
                                **Step 1:** Generate variations above
                                **Step 2:** Post each variation to your platform
                                **Step 3:** Track these metrics for each:
                                - Engagement rate (likes, comments, shares)
                                - Click-through rate (if applicable)
                                - Reach and impressions
                                - Save/bookmark rate
                                
                                **Step 4:** Use the best performer for future content
                                
                                **πŸ’‘ Pro Tips:**
                                - Test one element at a time for clear results
                                - Run tests for at least 7 days
                                - Use the same posting time and hashtags
                                - Need 1000+ views per variation for statistical significance
                                """)
        # Social Media Tab
        with gr.TabItem("πŸ“± Social Media Pack"):
            gr.Markdown("""
            ### Generate Platform-Optimized Images
            Create perfectly sized images for multiple social media platforms at once.
            """)
            with gr.Row():
                with gr.Column():
                    social_prompt = gr.Textbox(
                        label="Content Prompt",
                        placeholder="Describe your social media content...\nExample: Exciting announcement for new product launch",
                        lines=3
                    )
                    social_platforms = gr.CheckboxGroup(
                        choices=[
                            ("Instagram Post (1080x1080)", "instagram_post"),
                            ("Instagram Story (1080x1920)", "instagram_story"),
                            ("Twitter Post (1200x675)", "twitter_post"),
                            ("LinkedIn Post (1200x1200)", "linkedin_post"),
                            ("Facebook Cover (1200x630)", "facebook_cover"),
                            ("YouTube Thumbnail (1280x720)", "youtube_thumbnail")
                        ],
                        value=["instagram_post", "twitter_post"],
                        label="Select Platforms",
                        info="Each platform will get an optimized image"
                    )
                    social_steps = gr.Slider(
                        10, 100, 50,
                        label="Quality (Inference Steps)"
                    )
                    social_btn = gr.Button(
                        "πŸ“± Generate Social Pack", variant="primary", size="lg")

                with gr.Column():
                    social_output = gr.Gallery(
                        label="Platform-Optimized Images",
                        columns=2,
                        height="auto"
                    )
                    social_status = gr.Textbox(
                        label="Status", lines=4, interactive=False)

        with gr.TabItem("πŸ€– AI Prompt Assistant"):
            # Mobile-friendly header
            with gr.Column():
                gr.Markdown("### πŸ€– AI-Powered Prompt Creation")
                with gr.Accordion("πŸ’‘ How This Works", open=False):
                    gr.Markdown("""
                    **Simple 3-step process:**
                    1. Describe what you want in plain English
                    2. AI creates an optimized prompt  
                    3. Generate your professional image
                    """)
            
            # Main content - responsive layout
            with gr.Row():
                # Left column - Input section
                with gr.Column(scale=1, min_width=300):
                    ai_user_input = gr.Textbox(
                        label="What do you want to create?",
                        placeholder="Example: A hero image for my new eco-friendly water bottle product launch",
                        lines=4,
                        info="Describe your vision in plain language"
                    )
                    
                    # Mobile-friendly dropdown grid
                    with gr.Group():
                        gr.Markdown("#### Settings")
                        # Stack dropdowns vertically on mobile
                        ai_context = gr.Dropdown(
                            choices=[
                                ("General Marketing", "marketing"),
                                ("Product Photography", "product"),
                                ("Social Media Post", "social"),
                                ("Blog/Article Header", "blog"),
                                ("Event Promotion", "event"),
                                ("Brand Identity", "brand")
                            ],
                            value="marketing",
                            label="Content Type",
                            info="What are you creating?"
                        )
                        ai_style = gr.Dropdown(
                            choices=[
                                ("Professional", "professional"),
                                ("Playful & Fun", "playful"),
                                ("Minimalist", "minimalist"),
                                ("Luxury", "luxury"),
                                ("Tech/Modern", "tech"),
                                ("Natural/Organic", "natural")
                            ],
                            value="professional",
                            label="Style",
                            info="What mood to convey?"
                        )
                        ai_platform = gr.Dropdown(
                            choices=[
                                ("General Use", "general"),
                                ("Instagram", "instagram"),
                                ("Twitter/X", "twitter"),
                                ("LinkedIn", "linkedin"),
                                ("Facebook", "facebook"),
                                ("Website Hero", "website")
                            ],
                            value="general",
                            label="Platform",
                            info="Where will this be used?"
                        )
                    
                    # Generate button - full width
                    ai_generate_btn = gr.Button(
                        "πŸ€– Generate AI Prompt", 
                        variant="primary", 
                        size="lg",
                        scale=1
                    )
                    
                    # Quick examples - collapsible on mobile
                    with gr.Accordion("πŸ’­ Example Ideas", open=False):
                        gr.Examples(
                            examples=[
                                ["A hero image for my new eco-friendly water bottle", "product", "natural", "website"],
                                ["Announcement for our Black Friday sale", "social", "playful", "instagram"],
                                ["Professional headshots for company about page", "marketing", "professional", "linkedin"],
                                ["Blog header about AI in marketing", "blog", "tech", "general"],
                                ["Product showcase for luxury watch collection", "product", "luxury", "instagram"]
                            ],
                            inputs=[ai_user_input, ai_context, ai_style, ai_platform],
                            label=None
                        )

                # Right column - Output section
                with gr.Column(scale=1, min_width=300):
                    ai_generated_prompt = gr.Textbox(
                        label="AI-Generated Prompt",
                        lines=6,
                        interactive=True,
                        info="Edit this prompt if needed"
                    )
                    
                    ai_status = gr.Textbox(
                        label="Status",
                        lines=2,
                        interactive=False
                    )
                    
                    # Action buttons - stack on mobile
                    with gr.Row():
                        ai_use_prompt_btn = gr.Button(
                            "🎨 Generate Image", 
                            variant="primary",
                            scale=2
                        )
                        ai_save_prompt_btn = gr.Button(
                            "πŸ’Ύ Save to Single Tab", 
                            variant="secondary",
                            scale=1
                        )
                    
                    # Advanced options - collapsed by default
                    with gr.Accordion("πŸ”§ Advanced Prompt Refinement", open=False):
                        ai_improvement_request = gr.Textbox(
                            label="How to improve this prompt?",
                            placeholder="Example: Add more dramatic lighting, make it more colorful, include people",
                            lines=2
                        )
                        ai_improve_btn = gr.Button(
                            "✨ Improve Prompt", 
                            variant="secondary",
                            size="sm"
                        )
                    
                    # Preview image
                    ai_preview_image = gr.Image(
                        label="Generated Image Preview",
                        type="filepath",
                        visible=False,
                        height=300
                    )
            
            # Bottom tips section - full width
            with gr.Accordion("🎯 Pro Tips for Better Results", open=False):
                with gr.Row():
                    with gr.Column():
                        gr.Markdown("""
                        **Be Specific About:**
                        - **Subject**: What's the main focus?
                        - **Setting**: Where is it happening?
                        - **Mood**: What feeling to convey?
                        - **Colors**: Any specific palette?
                        """)
                    with gr.Column():
                        gr.Markdown("""
                        **Good Examples:**
                        - βœ… "Minimalist product photo of smartphone on marble"
                        - βœ… "Vibrant Instagram post for summer sale"
                        - ❌ "Product photo" (too vague)
                        - ❌ "Social media post" (not specific)
                        """)

    # Footer
    gr.Markdown("""
    ---
    ### πŸ› οΈ Powered by:
    - **Flux AI Model** - State-of-the-art image generation
    - **Modal Labs** - GPU infrastructure
    - **MCP Protocol** - Tool integration
    - **Gradio** - User interface
    
    Made with ❀️ for content creators and marketers
    """)

    # Event handlers
    single_btn.click(
        single_image_generation,
        inputs=[single_prompt, single_steps, single_style],
        outputs=[single_output, single_status]
    )

    batch_btn.click(
        enhanced_batch_generation,
        inputs=[batch_prompt,batch_variation_type, batch_count, batch_steps],
        outputs=[batch_output, batch_status]
    )
    batch_variation_type.change(
        update_strategy_info,
        inputs=[batch_variation_type],
        outputs=[strategy_info]
        )

    social_btn.click(
        social_media_generation,
        inputs=[social_prompt, social_platforms, social_steps],
        outputs=[social_output, social_status]
    )


    def generate_ai_prompt(user_input, context, style, platform):
        """Generate an optimized prompt using AI"""
        if not marketing_tool.is_connected:
            return "", "⚠️ MCP Server not connected. Please wait a few seconds and try again."

        if not user_input.strip():
            return "", "⚠️ Please describe what you want to create."

        try:
            request_id = f"ai_prompt_{time.time()}"
            marketing_tool.request_queue.put((
                "generate_prompt_with_ai",
                {
                    "user_input": user_input,
                    "context": context,
                    "style": style,
                    "platform": platform
                    },
                request_id
                ))
            status, result = wait_for_result(request_id, timeout=60)
            if status == "success":
                result_data = json.loads(result)
                if result_data.get("success"):
                    return result_data["prompt"], "βœ… AI prompt generated successfully!"
                else:
                    return result_data.get("fallback_prompt", ""), f"⚠️ Using fallback prompt: {result_data.get('error', 'Unknown error')}"
            else:
                return "", f"❌ Error: {result}"
        except Exception as e:
            return "", f"❌ Error: {str(e)}"
    ai_generate_btn.click(
        generate_ai_prompt,
        inputs=[ai_user_input, ai_context, ai_style, ai_platform],
        outputs=[ai_generated_prompt, ai_status]
    )
    
    def improve_ai_prompt(current_prompt, improvement_request):
        if not marketing_tool.is_connected:
            return current_prompt, "⚠️ MCP Server not connected."
        if not current_prompt.strip():
            return "", "⚠️ No prompt to improve. Generate one first."
        if not improvement_request.strip():
            return current_prompt, "⚠️ Please describe how you'd like to improve the prompt."
        try:
            enhanced_base = f"{current_prompt}. {improvement_request}"
            request_id = f"improve_prompt_{time.time()}"
            marketing_tool.request_queue.put((
                "enhance_prompt_with_details",  # Use the same tool
                {
                    "base_prompt": enhanced_base,
                    "enhancement_type": "detailed"
                    },
                request_id
                ))
            status, result = wait_for_result(request_id, timeout=60)
            if status == "success":
                if not result:
                    return current_prompt, "⚠️ Received empty response from server."
                try:
                    result_data = json.loads(result)
                    if result_data.get("success"):
                        return result_data["enhanced_prompt"], "βœ… Prompt improved successfully!"
                    else:
                        return current_prompt, f"⚠️ Could not improve prompt: {result_data.get('error', 'Unknown error')}"
                except json.JSONDecodeError as json_error:
                    print(f"JSON decode error: {json_error}")
                    print(f"Raw result: {repr(result)}")
                    return result if result else current_prompt, "βœ… Prompt improved (received as text)!"
                
            else:
                return current_prompt, f"❌ Error: {result}"
            
        except Exception as e:
            print(f"Exception in improve_ai_prompt: {str(e)}")
            return current_prompt, f"❌ Error: {str(e)}"
        
    ai_improve_btn.click(
        improve_ai_prompt,
        inputs=[ai_generated_prompt, ai_improvement_request],
        outputs=[ai_generated_prompt, ai_status]
    )
    
    def generate_image_from_ai_prompt(prompt, show_preview=True):
        if not prompt.strip():
            return None, "⚠️ Please generate a prompt first."
        image_path, status = single_image_generation(prompt, 50, "none")
        if show_preview and image_path:
            return gr.update(value=image_path, visible=True), status
        else:
            return gr.update(visible=False), status
        
    ai_use_prompt_btn.click(
        lambda prompt: generate_image_from_ai_prompt(prompt, True),
        inputs=[ai_generated_prompt],
        outputs=[ai_preview_image, ai_status]
    )
    ai_save_prompt_btn.click(
        lambda prompt: (prompt, "βœ… Prompt copied to Single Image tab!"),
        inputs=[ai_generated_prompt],
        outputs=[single_prompt, ai_status]
    ).then(
        lambda: gr.update(selected="πŸ–ΌοΈ Single Image"),
        outputs=[]
    )

    # Update connection status
    def update_connection_status():
        if marketing_tool.is_connected:
            return "βœ… **Connected to MCP Server** - Ready to generate!"
        else:
            return "πŸ”„ Connecting to MCP server... (please wait)"

    # Periodic status update
    demo.load(update_connection_status, outputs=[connection_status])

if __name__ == "__main__":
    print("Starting Marketing Content Generator...")
    print("Please wait for MCP server to initialize...")
    start_mcp_server()
    time.sleep(5)
    print("Launching Gradio interface...")
    demo.launch(share=False, mcp_server=True)