File size: 57,313 Bytes
cc07fc6
433de95
 
 
 
8012318
7b9bdd3
8012318
 
3d8e771
433de95
 
 
 
3d8e771
8012318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d8e771
 
 
 
 
8012318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d8e771
 
 
 
 
8012318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d8e771
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8012318
 
 
3d8e771
8012318
 
 
 
3d8e771
 
 
8012318
 
 
 
3d8e771
 
 
8012318
 
 
 
3d8e771
 
 
8012318
 
 
 
3d8e771
 
 
 
 
 
 
 
 
 
8012318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d8e771
 
7b9bdd3
8012318
3d8e771
8012318
 
 
 
 
 
 
 
 
3d8e771
8012318
 
3d8e771
 
 
 
 
 
 
 
8012318
3d8e771
8012318
3d8e771
8012318
3d8e771
8012318
 
3d8e771
 
 
 
 
 
 
 
 
 
8012318
 
3d8e771
 
8012318
3d8e771
8012318
3d8e771
8012318
3d8e771
 
8012318
3d8e771
8012318
3d8e771
 
8012318
3d8e771
8012318
3d8e771
 
 
 
 
 
8012318
3d8e771
 
8012318
3d8e771
 
 
 
 
 
8012318
3d8e771
8012318
 
 
3d8e771
 
 
 
 
 
8012318
3d8e771
 
 
 
 
8012318
3d8e771
8012318
3d8e771
8012318
3d8e771
 
 
 
 
 
8012318
3d8e771
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8012318
 
 
 
3d8e771
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8012318
3d8e771
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8012318
 
 
 
 
7b9bdd3
 
 
 
3d8e771
8012318
 
7b9bdd3
 
 
 
8012318
7b9bdd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8012318
7b9bdd3
8012318
3d8e771
 
 
7b9bdd3
3d8e771
7b9bdd3
 
8012318
3d8e771
8012318
 
 
3d8e771
8012318
 
 
3d8e771
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8012318
 
3d8e771
 
 
 
8012318
3d8e771
8012318
3d8e771
 
 
8012318
 
 
 
3d8e771
 
8012318
 
 
7b9bdd3
8012318
 
3d8e771
8012318
3d8e771
 
 
 
8012318
3d8e771
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8012318
3d8e771
8012318
3d8e771
8012318
 
7b9bdd3
3d8e771
433de95
7b9bdd3
 
433de95
7b9bdd3
 
979ed67
3d8e771
433de95
 
 
 
 
 
 
3d8e771
 
433de95
 
3d8e771
 
 
 
 
 
 
 
7b9bdd3
3d8e771
 
7b9bdd3
433de95
 
3d8e771
433de95
979ed67
433de95
979ed67
433de95
979ed67
433de95
7b9bdd3
3d8e771
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b9bdd3
3d8e771
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b9bdd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8012318
7b9bdd3
 
 
 
 
 
 
 
 
 
 
 
 
 
433de95
 
 
 
 
 
 
 
 
4e23d03
433de95
4e23d03
 
433de95
4e23d03
433de95
4e23d03
 
433de95
 
 
 
9758d74
3d8e771
 
7b9bdd3
9758d74
7b9bdd3
 
 
979ed67
3d8e771
433de95
 
3d8e771
 
 
7b9bdd3
433de95
7b9bdd3
 
 
 
433de95
3d8e771
 
 
 
 
7b9bdd3
 
3d8e771
 
 
7b9bdd3
3d8e771
 
47cfce2
7b9bdd3
 
3d8e771
7b9bdd3
 
3d8e771
a2e798a
7b9bdd3
3d8e771
 
 
 
433de95
3d8e771
7b9bdd3
 
3d8e771
7b9bdd3
 
3d8e771
 
 
 
7b9bdd3
 
 
3d8e771
 
7b9bdd3
3d8e771
7b9bdd3
 
3d8e771
 
 
 
 
433de95
3d8e771
7b9bdd3
 
3d8e771
 
 
7b9bdd3
3d8e771
7b9bdd3
 
 
 
 
3d8e771
 
 
 
 
7b9bdd3
 
3d8e771
7b9bdd3
3d8e771
7b9bdd3
 
 
 
 
 
 
 
 
 
3d8e771
 
 
 
 
 
 
 
7b9bdd3
 
 
3d8e771
7b9bdd3
 
 
 
3d8e771
 
7b9bdd3
3d8e771
7b9bdd3
 
 
 
3d8e771
7b9bdd3
3d8e771
 
 
 
 
7b9bdd3
3d8e771
 
 
 
 
433de95
3d8e771
 
7b9bdd3
 
 
 
 
3d8e771
7b9bdd3
 
 
 
 
 
3d8e771
 
7b9bdd3
 
 
 
 
 
 
 
 
3d8e771
7b9bdd3
 
 
3d8e771
433de95
7b9bdd3
3d8e771
7b9bdd3
3d8e771
 
 
7b9bdd3
 
 
3d8e771
 
7b9bdd3
 
 
 
 
 
3d8e771
7b9bdd3
 
 
 
3d8e771
7b9bdd3
3d8e771
7b9bdd3
3d8e771
 
7b9bdd3
 
 
 
3d8e771
7b9bdd3
3d8e771
7b9bdd3
3d8e771
 
 
 
7b9bdd3
3d8e771
433de95
 
 
7b9bdd3
 
433de95
 
7b9bdd3
3d8e771
 
7b9bdd3
 
 
 
 
 
 
 
 
3d8e771
 
 
 
 
7b9bdd3
433de95
 
3d8e771
979ed67
4e23d03
 
 
 
 
 
7b9bdd3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
import gradio as gr
import google.generativeai as genai
import os
from dotenv import load_dotenv
import time
import json
import markdown # Ensure markdown is imported
import base64
from datetime import datetime
import re

# Load environment variables from .env file if it exists
load_dotenv()

# Enhanced templates for different food niches
DEFAULT_TEMPLATES = {
    "fermentation": """
Act as an elite-level SEO strategist and content creator with deep expertise in food blogs, particularly fermentation. I run a blog about fermentation, and my primary goal is to increase organic traffic, educate beginners, and establish thought leadership. My target audience is beginners curious about home fermentation and health-conscious individuals.
For the specific topic: '{topic}'
Analyze and generate a comprehensive SEO content plan designed to rank highly on Google and provide exceptional user value. Ensure all outputs adhere to E-E-A-T principles.
I require the following, formatted in clean markdown:
1.  **Strategic Keyword Analysis:**
    *   **Primary Target Keyword:**
    *   **Secondary Keywords:** 2-3 closely related, high-intent keywords.
    *   **Long-Tail Keywords & User Questions:** 5-7 specific user-searched phrases.
    *   **Semantic/LSI Keywords:** 5-7 contextually related terms.
    *   **Search Intent Analysis:** (Informational, Commercial, etc.)
2.  **Competitive Landscape Overview (Top 3-5 Competitors):**
    *   For each:
        *   URL
        *   Strengths
        *   Weaknesses
        *   Content angle/hook
3.  **Content Gaps & Unique Value Proposition:**
    *   Missing topics or angles
    *   Unique insights or differentiators for *my* blog
4.  **Optimized Blog Post Outline:**
    *   **H1 Title:**
    *   **Meta Description:** (under 160 characters)
    *   **Full H2/H3 outline:**
    *   **Suggested Visuals:** Where applicable
5.  **User-Focused FAQ Section:** 3–5 related to '{topic}'
6.  **Internal & External Linking Plan:**
    *   **Internal:** 2-3 relevant articles with anchor suggestions
    *   **External:** 1-2 reputable sources (.edu, .org, studies)
7.  **E-E-A-T Enhancements:**
    *   1-2 ways to show experience, trust, and authority in the content
8.  **SEO Performance Metrics:**
    *   Expected keyword difficulty (1-100)
    *   Estimated monthly search volume
    *   Content length recommendation
    *   Target reading time
""",
    "baking": """
Act as an elite-level SEO strategist and content creator with deep expertise in food blogs, particularly baking and pastry. I run a blog about baking, and my primary goal is to increase organic traffic, help home bakers improve their skills, and showcase unique recipes. My target audience is home bakers of all skill levels looking for reliable recipes and techniques.
For the specific topic: '{topic}'
Analyze and generate a comprehensive SEO content plan designed to rank highly on Google and provide exceptional user value. Ensure all outputs adhere to E-E-A-T principles.
I require the following, formatted in clean markdown:
1.  **Strategic Keyword Analysis:**
    *   **Primary Target Keyword:**
    *   **Secondary Keywords:** 2-3 closely related, high-intent keywords.
    *   **Long-Tail Keywords & User Questions:** 5-7 specific user-searched phrases.
    *   **Seasonal/Holiday Keywords:** 2-3 if applicable
    *   **Search Intent Analysis:** (Recipe-seeking, Technique-learning, Equipment-buying, etc.)
2.  **Competitive Landscape Overview (Top 3-5 Competitors):**
    *   For each:
        *   URL
        *   Recipe uniqueness/approach
        *   Visual presentation
        *   User engagement factors
3.  **Recipe Uniqueness & Value Proposition:**
    *   Distinctive ingredients or techniques
    *   How my recipe differs from competitors
    *   Troubleshooting common issues other recipes don't address
4.  **Optimized Blog Post Outline:**
    *   **H1 Title:**
    *   **Meta Description:** (under 160 characters)
    *   **Full H2/H3 outline** (including "Why This Recipe Works", "Ingredients", "Step-by-Step Instructions", "Storage & Make-Ahead Tips")
    *   **Recipe Schema Markup Elements:**
    *   **Required Photo/Video Content:**
5.  **User-Focused FAQ Section:** 3–5 related to '{topic}'
6.  **Internal & External Linking Plan:**
    *   **Internal:** 2-3 relevant recipes with anchor suggestions
    *   **External:** 1-2 reputable sources for techniques or ingredient information
7.  **E-E-A-T Enhancements:**
    *   Recipe testing notes to include
    *   Personal experience elements to highlight
    *   Scientific explanation opportunities
8.  **SEO Performance Metrics:**
    *   Expected keyword difficulty (1-100)
    *   Estimated monthly search volume
    *   Content length recommendation
    *   Recipe card optimization tips
""",
    "plant_based": """
Act as an elite-level SEO strategist and content creator with deep expertise in plant-based and vegan food blogs. I run a blog about plant-based cooking, and my primary goal is to increase organic traffic, help people transition to more plant-based eating, and provide delicious alternatives to animal products. My target audience includes vegans, vegetarians, flexitarians, and the plant-curious.
For the specific topic: '{topic}'
Analyze and generate a comprehensive SEO content plan designed to rank highly on Google and provide exceptional user value. Ensure all outputs adhere to E-E-A-T principles.
I require the following, formatted in clean markdown:
1.  **Strategic Keyword Analysis:**
    *   **Primary Target Keyword:**
    *   **Secondary Keywords:** 2-3 closely related, high-intent keywords.
    *   **Long-Tail Keywords & User Questions:** 5-7 specific user-searched phrases.
    *   **Dietary Restriction Related Keywords:** (gluten-free, nut-free, soy-free, etc.)
    *   **Search Intent Analysis:** (Recipe-seeking, Nutrition information, Substitution help, etc.)
2.  **Competitive Landscape Overview (Top 3-5 Competitors):**
    *   For each:
        *   URL
        *   Ingredient approach (whole foods vs. processed substitutes)
        *   Nutritional information provided
        *   User engagement factors
3.  **Plant-Based Value Proposition:**
    *   Health/nutritional benefits to highlight
    *   Environmental/ethical angle if applicable
    *   Taste/texture comparisons to non-vegan alternatives
    *   Accessibility of ingredients
4.  **Optimized Blog Post Outline:**
    *   **H1 Title:**
    *   **Meta Description:** (under 160 characters)
    *   **Full H2/H3 outline** (including "Why Choose Plant-Based", "Ingredients & Substitutions", "Step-by-Step Instructions", "Nutritional Information")
    *   **Recipe Schema Markup Elements:**
    *   **Required Photo Content:**
5.  **User-Focused FAQ Section:** 3–5 related to '{topic}' (focusing on common substitution questions)
6.  **Internal & External Linking Plan:**
    *   **Internal:** 2-3 relevant recipes with anchor suggestions
    *   **External:** 1-2 reputable sources for nutritional information
7.  **E-E-A-T Enhancements:**
    *   Nutritional expertise to highlight
    *   Personal experience with plant-based eating
    *   Scientific/research citations to include
8.  **SEO Performance Metrics:**
    *   Expected keyword difficulty (1-100)
    *   Estimated monthly search volume
    *   Nutritional content optimization
    *   Health claim compliance
""",
    "keto": """
Act as an elite-level SEO strategist and content creator with deep expertise in keto and low-carb food blogs. I run a blog about ketogenic recipes and lifestyle, and my primary goal is to increase organic traffic, help people succeed on keto, and provide delicious low-carb alternatives. My target audience includes keto beginners, experienced keto dieters, and low-carb enthusiasts.
For the specific topic: '{topic}'
Analyze and generate a comprehensive SEO content plan designed to rank highly on Google and provide exceptional user value. Ensure all outputs adhere to E-E-A-T principles.
I require the following, formatted in clean markdown:
1.  **Strategic Keyword Analysis:**
    *   **Primary Target Keyword:**
    *   **Secondary Keywords:** 2-3 closely related, high-intent keywords.
    *   **Long-Tail Keywords & User Questions:** 5-7 specific user-searched phrases.
    *   **Keto-Specific Keywords:** (net carbs, macros, ketosis, etc.)
    *   **Search Intent Analysis:** (Recipe-seeking, Macro information, Keto compliance, etc.)
2.  **Competitive Landscape Overview (Top 3-5 Competitors):**
    *   For each:
        *   URL
        *   Macro accuracy and presentation
        *   Keto compliance verification
        *   User engagement factors
3.  **Keto Value Proposition:**
    *   Net carb calculations
    *   Macro breakdown (fat/protein/carb ratios)
    *   Ketone production potential
    *   Satiety and weight loss benefits
4.  **Optimized Blog Post Outline:**
    *   **H1 Title:**
    *   **Meta Description:** (under 160 characters)
    *   **Full H2/H3 outline** (including "Why This Recipe is Keto", "Ingredients & Net Carbs", "Step-by-Step Instructions", "Macro Information")
    *   **Recipe Schema Markup Elements:**
    *   **Required Macro Charts/Tables:**
5.  **User-Focused FAQ Section:** 3–5 related to '{topic}' (focusing on keto compliance questions)
6.  **Internal & External Linking Plan:**
    *   **Internal:** 2-3 relevant keto recipes with anchor suggestions
    *   **External:** 1-2 reputable sources for nutritional/keto information
7.  **E-E-A-T Enhancements:**
    *   Nutritional expertise to highlight
    *   Personal keto experience elements
    *   Scientific/research citations for keto benefits
8.  **SEO Performance Metrics:**
    *   Expected keyword difficulty (1-100)
    *   Estimated monthly search volume
    *   Macro accuracy requirements
    *   Keto community engagement potential
""",
    "mediterranean": """
Act as an elite-level SEO strategist and content creator with deep expertise in Mediterranean cuisine and healthy food blogs. I run a blog about Mediterranean cooking and lifestyle, and my primary goal is to increase organic traffic, promote healthy eating habits, and share authentic Mediterranean recipes. My target audience includes health-conscious individuals, Mediterranean diet followers, and those interested in longevity and wellness.
For the specific topic: '{topic}'
Analyze and generate a comprehensive SEO content plan designed to rank highly on Google and provide exceptional user value. Ensure all outputs adhere to E-E-A-T principles.
I require the following, formatted in clean markdown:
1.  **Strategic Keyword Analysis:**
    *   **Primary Target Keyword:**
    *   **Secondary Keywords:** 2-3 closely related, high-intent keywords.
    *   **Long-Tail Keywords & User Questions:** 5-7 specific user-searched phrases.
    *   **Health-Focused Keywords:** (heart-healthy, anti-inflammatory, longevity, etc.)
    *   **Search Intent Analysis:** (Recipe-seeking, Health information, Cultural learning, etc.)
2.  **Competitive Landscape Overview (Top 3-5 Competitors):**
    *   For each:
        *   URL
        *   Authenticity approach
        *   Health benefit emphasis
        *   Cultural storytelling elements
3.  **Mediterranean Value Proposition:**
    *   Health benefits (heart health, longevity, etc.)
    *   Cultural authenticity and traditions
    *   Ingredient quality and sourcing
    *   Lifestyle integration aspects
4.  **Optimized Blog Post Outline:**
    *   **H1 Title:**
    *   **Meta Description:** (under 160 characters)
    *   **Full H2/H3 outline** (including "Mediterranean Diet Benefits", "Authentic Ingredients", "Step-by-Step Instructions", "Cultural Context")
    *   **Recipe Schema Markup Elements:**
    *   **Required Cultural/Historical Context:**
5.  **User-Focused FAQ Section:** 3–5 related to '{topic}' (focusing on health and authenticity questions)
6.  **Internal & External Linking Plan:**
    *   **Internal:** 2-3 relevant Mediterranean recipes with anchor suggestions
    *   **External:** 1-2 reputable sources for health research or cultural information
7.  **E-E-A-T Enhancements:**
    *   Cultural expertise or travel experience
    *   Health research citations
    *   Traditional cooking method explanations
8.  **SEO Performance Metrics:**
    *   Expected keyword difficulty (1-100)
    *   Estimated monthly search volume
    *   Health content optimization
    *   Cultural authenticity factors
""",
    "desserts": """
Act as an elite-level SEO strategist and content creator with deep expertise in dessert and pastry blogs. I run a blog about desserts and sweet treats, and my primary goal is to increase organic traffic, help home bakers create impressive desserts, and share both classic and innovative sweet recipes. My target audience includes dessert lovers, home bakers, and those looking for special occasion treats.
For the specific topic: '{topic}'
Analyze and generate a comprehensive SEO content plan designed to rank highly on Google and provide exceptional user value. Ensure all outputs adhere to E-E-A-T principles.
I require the following, formatted in clean markdown:
1.  **Strategic Keyword Analysis:**
    *   **Primary Target Keyword:**
    *   **Secondary Keywords:** 2-3 closely related, high-intent keywords.
    *   **Long-Tail Keywords & User Questions:** 5-7 specific user-searched phrases.
    *   **Occasion-Specific Keywords:** (birthday, holiday, celebration, etc.)
    *   **Search Intent Analysis:** (Recipe-seeking, Technique learning, Decoration ideas, etc.)
2.  **Competitive Landscape Overview (Top 3-5 Competitors):**
    *   For each:
        *   URL
        *   Visual presentation quality
        *   Technique explanation depth
        *   User engagement factors
3.  **Dessert Value Proposition:**
    *   Difficulty level and skill requirements
    *   Visual appeal and presentation
    *   Flavor profiles and uniqueness
    *   Make-ahead and storage options
4.  **Optimized Blog Post Outline:**
    *   **H1 Title:**
    *   **Meta Description:** (under 160 characters)
    *   **Full H2/H3 outline** (including "Why This Dessert Works", "Ingredients & Substitutions", "Step-by-Step Instructions", "Decoration Tips", "Storage & Serving")
    *   **Recipe Schema Markup Elements:**
    *   **Required Photo/Video Content:**
5.  **User-Focused FAQ Section:** 3–5 related to '{topic}' (focusing on technique and troubleshooting questions)
6.  **Internal & External Linking Plan:**
    *   **Internal:** 2-3 relevant dessert recipes with anchor suggestions
    *   **External:** 1-2 reputable sources for technique or ingredient information
7.  **E-E-A-T Enhancements:**
    *   Baking expertise and testing notes
    *   Personal experience with techniques
    *   Scientific explanations for baking chemistry
8.  **SEO Performance Metrics:**
    *   Expected keyword difficulty (1-100)
    *   Estimated monthly search volume
    *   Visual content requirements
    *   Seasonal/occasion optimization
"""
}

# Enhanced language settings with keyword suggestions
LANGUAGE_SETTINGS = {
    "English": {
        "search_engines": ["Google", "Bing", "DuckDuckGo"],
        "localization_tips": "Focus on English-speaking markets (US, UK, Canada, Australia)",
        "keyword_examples": ["recipe", "how to", "benefits of", "best", "easy", "homemade", "healthy", "quick", "simple", "ultimate"],
        "long_tail_patterns": ["how to make", "best way to", "easy recipe for", "homemade", "step by step", "beginner's guide to"],
        "question_keywords": ["what is", "why does", "how long", "can you", "is it safe", "what are the benefits"]
    },
    "Spanish": {
        "search_engines": ["Google", "Bing", "Yahoo"],
        "localization_tips": "Target Spain and Latin American markets with regional variants",
        "keyword_examples": ["receta", "cΓ³mo hacer", "beneficios de", "mejor", "fΓ‘cil", "casero", "saludable", "rΓ‘pido", "sencillo", "definitivo"],
        "long_tail_patterns": ["cΓ³mo hacer", "mejor manera de", "receta fΓ‘cil de", "casero", "paso a paso", "guΓ­a para principiantes"],
        "question_keywords": ["quΓ© es", "por quΓ©", "cuΓ‘nto tiempo", "se puede", "es seguro", "cuΓ‘les son los beneficios"]
    },
    "French": {
        "search_engines": ["Google", "Qwant", "Bing"],
        "localization_tips": "Focus on France, Belgium, Canada (Quebec), Switzerland",
        "keyword_examples": ["recette", "comment faire", "avantages de", "meilleur", "facile", "fait maison", "sain", "rapide", "simple", "ultime"],
        "long_tail_patterns": ["comment faire", "meilleure faΓ§on de", "recette facile de", "fait maison", "Γ©tape par Γ©tape", "guide pour dΓ©butants"],
        "question_keywords": ["qu'est-ce que", "pourquoi", "combien de temps", "peut-on", "est-ce sΓ»r", "quels sont les avantages"]
    },
    "German": {
        "search_engines": ["Google", "Bing", "Yahoo"],
        "localization_tips": "Target Germany, Austria, Switzerland with appropriate dialect considerations",
        "keyword_examples": ["rezept", "wie man", "vorteile von", "beste", "einfach", "hausgemacht", "gesund", "schnell", "einfach", "ultimativ"],
        "long_tail_patterns": ["wie man macht", "beste Art zu", "einfaches Rezept fΓΌr", "hausgemacht", "Schritt fΓΌr Schritt", "AnfΓ€ngerfΓΌhrer fΓΌr"],
        "question_keywords": ["was ist", "warum", "wie lange", "kann man", "ist es sicher", "was sind die Vorteile"]
    },
    "Italian": {
        "search_engines": ["Google", "Bing", "Yahoo"],
        "localization_tips": "Target Italy with regional food variations and local ingredients",
        "keyword_examples": ["ricetta", "come fare", "benefici di", "migliore", "facile", "fatto in casa", "sano", "veloce", "semplice", "perfetto"],
        "long_tail_patterns": ["come fare", "modo migliore per", "ricetta facile di", "fatto in casa", "passo dopo passo", "guida per principianti"],
        "question_keywords": ["cos'Γ¨", "perchΓ©", "quanto tempo", "si puΓ²", "Γ¨ sicuro", "quali sono i benefici"]
    }
}

# Function to save templates to file
def save_templates():
    with open("templates.json", "w") as f:
        json.dump(DEFAULT_TEMPLATES, f, indent=4)
    
    with open("languages.json", "w") as f:
        json.dump(LANGUAGE_SETTINGS, f, indent=4)

# Load templates if they exist, otherwise use defaults
def load_templates():
    templates = DEFAULT_TEMPLATES.copy()
    languages = LANGUAGE_SETTINGS.copy()
    
    try:
        if os.path.exists("templates.json"):
            with open("templates.json", "r") as f:
                templates = json.load(f)
    except Exception as e:
        print(f"Error loading templates: {e}")
    
    try:
        if os.path.exists("languages.json"):
            with open("languages.json", "r") as f:
                languages = json.load(f)
    except Exception as e:
        print(f"Error loading languages: {e}")
    
    return templates, languages

# Initialize templates
TEMPLATES, LANGUAGES = load_templates()

# Enhanced HTML export with better styling and SEO metrics
def generate_html_export(content, title, template_type, language):
    # content here is expected to be MARKDOWN
    html_template = f"""<!DOCTYPE html>
<html lang="{language.lower()[:2]}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{title} - SEO Plan</title>
    <style>
        body {{
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
        }}
        
        .container {{
            background-color: white;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            overflow: hidden;
        }}
        
        header {{
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }}
        
        .header-info {{
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 20px;
            font-size: 0.9em;
            opacity: 0.9;
        }}
        
        h1 {{
            margin: 0;
            font-size: 2.2em;
            font-weight: 300;
        }}
        
        h2 {{
            border-bottom: 3px solid #667eea;
            padding-bottom: 10px;
            color: #4c51bf;
            margin-top: 30px;
        }}
        
        h3 {{
            color: #553c9a;
            margin-top: 25px;
        }}
        
        .content {{
            padding: 40px;
        }}
        
        .metrics-box {{
            background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
            border-left: 5px solid #f56565;
        }}
        
        .keyword-box {{
            background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
            padding: 15px;
            border-radius: 8px;
            margin: 15px 0;
        }}
        
        ul {{
            margin-left: 20px;
        }}
        
        li {{
            margin-bottom: 8px;
            padding-left: 5px;
        }}
        
        code {{
            background-color: #f7fafc;
            padding: 3px 6px;
            border-radius: 4px;
            font-family: 'Monaco', 'Consolas', monospace;
            border: 1px solid #e2e8f0;
        }}
        
        blockquote {{
            border-left: 4px solid #667eea;
            margin-left: 0;
            padding-left: 20px;
            color: #4a5568;
            font-style: italic;
            background-color: #f7fafc;
            padding: 15px 20px;
            border-radius: 0 8px 8px 0;
        }}
        
        .export-info {{
            background-color: #edf2f7;
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
            border: 1px solid #cbd5e0;
        }}
        
        footer {{
            background-color: #2d3748;
            color: white;
            padding: 20px;
            text-align: center;
        }}
        
        .print-button {{
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin: 10px;
        }}
        
        @media print {{
            body {{ background: white; }}
            .container {{ box-shadow: none; }}
            .print-button {{ display: none; }}
        }}
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>{title} - SEO Content Strategy</h1>
            <div class="header-info">
                <span>πŸ“Š Template: {template_type.title()}</span>
                <span>🌐 Language: {language}</span>
                <span>πŸ“… Generated: {datetime.now().strftime("%B %d, %Y at %H:%M")}</span>
            </div>
        </header>
        
        <div class="content">
            <div class="export-info">
                <strong>πŸ“‹ Export Information:</strong><br>
                This SEO plan was generated using AI analysis and industry best practices. 
                Use this as a strategic guide for your content creation process.
                <button class="print-button" onclick="window.print()">πŸ–¨οΈ Print/Save as PDF</button>
            </div>
            
            {markdown.markdown(content)}
        </div>
        
        <footer>
            <p>πŸš€ Generated using Enhanced SEO Assistant | 
            Template: {template_type.title()} | 
            Language: {language} | 
            AI-Powered Content Strategy</p>
        </footer>
    </div>
    
    <script>
        // Add some interactivity
        document.addEventListener('DOMContentLoaded', function() {{
            // Highlight keywords in content
            const keywords = document.querySelectorAll('code');
            keywords.forEach(keyword => {{
                keyword.style.cursor = 'pointer';
                keyword.addEventListener('click', function() {{
                    navigator.clipboard.writeText(this.textContent);
                    this.style.backgroundColor = '#48bb78';
                    this.style.color = 'white';
                    setTimeout(() => {{
                        this.style.backgroundColor = '#f7fafc';
                        this.style.color = '#2d3748';
                    }}, 1000);
                }});
            }});
        }});
    </script>
</body>
</html>
"""
    return html_template

# Export the SEO plan as STYLED HTML and create download link
def export_styled_html(markdown_content, topic, template_type, language):
    # markdown_content is the raw markdown from the AI
    if not markdown_content or markdown_content.startswith("⚠️") or markdown_content.startswith("πŸ”„") or markdown_content == "<p>Your comprehensive SEO plan will appear here...</p>" or markdown_content == "Your comprehensive SEO plan will appear here...":
        return "Please generate an SEO plan first.", None
    
    title = topic.strip().title()
    html_content_to_save = generate_html_export(markdown_content, title, template_type, language)
    
    safe_filename = "".join([c if c.isalnum() or c in " -_" else "_" for c in title])
    safe_filename = f"{safe_filename}_{template_type}_{language}_Styled_SEO_Plan.html".replace(" ", "_")
    
    try:
        with open(safe_filename, "w", encoding="utf-8") as f:
            f.write(html_content_to_save)
        return f"βœ… Styled HTML export saved as '{safe_filename}'", safe_filename
    except Exception as e:
        return f"❌ Error saving styled HTML file: {str(e)}", None

# Export the DISPLAYED HTML content (which is already HTML)
def export_displayed_html(html_content, topic):
    # html_content is the HTML string from the gr.HTML component
    placeholder_html = "<p>Your comprehensive SEO plan will appear here...</p>"
    if not html_content or html_content == placeholder_html or html_content.startswith("⚠️") or html_content.startswith("πŸ”„") or html_content.startswith("πŸ“") or html_content.startswith("✨") or html_content.startswith("🧠") or html_content.startswith("πŸš€"): # Check for various states
        return "Please generate and finalize an SEO plan first.", None

    title = topic.strip().title() if topic.strip() else "Generated_Content"
    safe_filename = "".join([c if c.isalnum() or c in " -_" else "_" for c in title])
    safe_filename = f"{safe_filename}_Displayed_Content.html".replace(" ", "_")
    
    try:
        with open(safe_filename, "w", encoding="utf-8") as f:
            f.write(html_content)
        return f"βœ… Displayed HTML content saved as '{safe_filename}'", safe_filename
    except Exception as e:
        return f"❌ Error saving displayed HTML file: {str(e)}", None


# Enhanced template management
def save_custom_template(template_name, template_content):
    if not template_name or not template_content:
        return "⚠️ Please provide both a template name and content."
    TEMPLATES[template_name.lower().replace(" ", "_")] = template_content
    save_templates()
    return f"βœ… Template '{template_name}' saved successfully!"

def delete_template(template_name):
    if template_name in TEMPLATES:
        if template_name in DEFAULT_TEMPLATES:
            return "⚠️ Cannot delete default templates."
        del TEMPLATES[template_name]
        save_templates()
        return f"βœ… Template '{template_name}' deleted successfully!"
    else:
        return f"⚠️ Template '{template_name}' not found."

def load_template_content(template_name):
    if template_name in TEMPLATES:
        return TEMPLATES[template_name]
    return ""

def get_template_list():
    return list(TEMPLATES.keys())

# Enhanced language settings management
def save_language_settings(language_name, search_engines, localization_tips, keyword_examples, long_tail_patterns, question_keywords):
    if not language_name:
        return "⚠️ Please provide a language name."
    search_engines_list = [se.strip() for se in search_engines.split(",") if se.strip()]
    keyword_examples_list = [kw.strip() for kw in keyword_examples.split(",") if kw.strip()]
    long_tail_list = [lt.strip() for lt in long_tail_patterns.split(",") if lt.strip()]
    question_list = [q.strip() for q in question_keywords.split(",") if q.strip()]
    LANGUAGES[language_name] = {
        "search_engines": search_engines_list,
        "localization_tips": localization_tips,
        "keyword_examples": keyword_examples_list,
        "long_tail_patterns": long_tail_list,
        "question_keywords": question_list
    }
    save_templates()
    return f"βœ… Language settings for '{language_name}' saved successfully!"

# Enhanced prompt building with advanced features
def build_prompt(topic, template_key="fermentation", language="English", include_advanced_metrics=True):
    if template_key in TEMPLATES:
        template = TEMPLATES[template_key]
    else:
        template = TEMPLATES["fermentation"]
    lang_settings = LANGUAGES.get(language, LANGUAGES["English"])
    language_instructions = f"""
LANGUAGE & LOCALIZATION OPTIMIZATION FOR {language.upper()}:
1. **Target Search Engines:** {', '.join(lang_settings['search_engines'])}
2. **Localization Strategy:** {lang_settings['localization_tips']}
3. **Primary Keyword Patterns:** {', '.join(lang_settings['keyword_examples'])}
4. **Long-tail Keyword Patterns:** {', '.join(lang_settings.get('long_tail_patterns', []))}
5. **Question-based Keywords:** {', '.join(lang_settings.get('question_keywords', []))}
"""
    if include_advanced_metrics:
        advanced_metrics = """
ADVANCED SEO METRICS TO INCLUDE:
9. **Content Performance Analysis:**
   * Recommended content length (word count)
   * Target reading time
   * Keyword density recommendations
   * Readability score target (Flesch-Kincaid)
   * Mobile optimization considerations
10. **AI-Powered Content Suggestions:**
    * Trending subtopics to include
    * Related questions people are asking
    * Seasonal content opportunities
    * Social media content ideas
    * Email marketing angles
11. **Technical SEO Considerations:**
    * Page speed optimization tips
    * Image optimization requirements
    * Schema markup recommendations
    * Internal linking architecture
    * URL structure suggestions
12. **Content Distribution Strategy:**
    * Social media promotion angles
    * Email newsletter content ideas
    * Pinterest optimization tips
    * YouTube video content suggestions
    * Podcast episode ideas
"""
    else:
        advanced_metrics = ""
    if language != "English":
        full_template = template + "\n\n" + language_instructions + advanced_metrics
    else:
        full_template = template + "\n\n" + advanced_metrics
    return full_template.format(topic=topic)

# Enhanced SEO generation with streaming (YIELDS MARKDOWN)
def generate_seo_plan(topic, api_key, template_key="fermentation", language="English", temperature=0.7, max_tokens=6000, include_advanced_metrics=True):
    if not topic.strip():
        yield "⚠️ Please enter a topic to generate an SEO plan."
        return
    if not api_key.strip():
        yield "⚠️ Please provide your Gemini API key."
        return
    
    yield "πŸ”„ Initializing Enhanced SEO Assistant..."
    try:
        genai.configure(api_key=api_key)
        model = genai.GenerativeModel(
            "gemini-1.5-pro",
            generation_config={
                "temperature": float(temperature),
                "max_output_tokens": max_tokens,
                "top_p": 0.95,
                "top_k": 40
            }
        )
        yield f"🧠 Building enhanced SEO prompt for {template_key} niche in {language}..."
        prompt = build_prompt(topic, template_key, language, include_advanced_metrics)
        yield "πŸš€ Generating comprehensive SEO plan with Gemini 1.5 Pro..."
        response = model.generate_content(prompt, stream=True)
        full_response = ""
        for chunk in response:
            if chunk.text:
                full_response += chunk.text
                yield "πŸ“ " + full_response
        yield "✨ Finalizing your enhanced SEO plan..."
        time.sleep(0.5)
        yield full_response # This is the final MARKDOWN
    except Exception as e:
        error_message = str(e)
        print(f"Error generating SEO plan: {error_message}")
        if "API key not valid" in error_message or "authentication" in error_message.lower():
            yield "⚠️ API Key Error: The provided Gemini API key appears to be invalid. Please check your key and try again."
        elif "quota" in error_message.lower():
            yield "⚠️ Quota Exceeded: Your Gemini API quota has been exceeded. Please check your Google AI Studio dashboard."
        else:
            yield f"⚠️ Error: {error_message}"

# AI-powered content suggestions (RETURNS MARKDOWN)
def generate_content_ideas(topic, api_key, template_key="fermentation", language="English"):
    if not topic.strip() or not api_key.strip():
        return "⚠️ Please provide both a topic and API key."
    try:
        genai.configure(api_key=api_key)
        model = genai.GenerativeModel("gemini-1.5-pro")
        prompt = f"""
As an AI content strategist specializing in {template_key} content, generate creative content ideas for the topic: "{topic}"
Please provide:
1. **5 Related Blog Post Ideas:**
   - Complementary topics that would work well together
   - Different angles on the same subject
2. **Social Media Content Ideas:**
   - 3 Instagram post concepts
   - 3 TikTok/Reel ideas
   - 2 Pinterest pin concepts
3. **Email Marketing Angles:**
   - Welcome series email ideas
   - Newsletter content suggestions
4. **Video Content Opportunities:**
   - YouTube video concepts
   - Short-form video ideas
5. **Seasonal Content Calendar:**
   - Monthly content themes
   - Holiday tie-ins
6. **User-Generated Content Ideas:**
   - Contest/challenge concepts
   - Community engagement strategies
Format in clean markdown with actionable suggestions.
"""
        response = model.generate_content(prompt)
        return response.text
    except Exception as e:
        return f"⚠️ Error generating content ideas: {str(e)}"

# Keyword research enhancement (RETURNS MARKDOWN)
def generate_keyword_research(topic, api_key, language="English", competition_level="medium"):
    if not topic.strip() or not api_key.strip():
        return "⚠️ Please provide both a topic and API key."
    try:
        genai.configure(api_key=api_key)
        model = genai.GenerativeModel("gemini-1.5-pro")
        lang_settings = LANGUAGES.get(language, LANGUAGES["English"])
        prompt = f"""
As an SEO keyword research specialist, provide comprehensive keyword analysis for: "{topic}" in {language}
Target competition level: {competition_level}
Please provide:
1. **Primary Keywords (3-5):**
   - High search volume, {competition_level} competition
   - Include estimated monthly searches
2. **Long-tail Keywords (10-15):**
   - Lower competition, more specific
   - Question-based keywords using patterns: {', '.join(lang_settings.get('question_keywords', []))}
3. **Semantic Keywords (8-10):**
   - Related terms and synonyms
   - LSI keywords for content depth
4. **Local SEO Keywords (if applicable):**
   - Location-based variations
   - "Near me" variations
5. **Competitor Keywords:**
   - What competitors are likely ranking for
   - Keyword gaps to exploit
6. **Trending Keywords:**
   - Seasonal trends
   - Emerging topics in this niche
7. **Conversion-Focused Keywords:**
   - Commercial intent keywords
   - Buyer journey keywords
Provide keyword difficulty estimates (1-100) and search volume estimates for each category.
Format in clean markdown with actionable insights.
"""
        response = model.generate_content(prompt)
        return response.text
    except Exception as e:
        return f"⚠️ Error generating keyword research: {str(e)}"

# Wrapper for generate_seo_plan to handle streaming and HTML conversion
def stream_and_convert_seo_plan_wrapper(topic, api_key, template_key, language, temperature, max_tokens, include_advanced_metrics):
    latest_raw_markdown = ""
    initial_placeholder_html = "<p>Your comprehensive SEO plan will appear here...</p>" # Used to avoid processing placeholder

    for output_from_generator in generate_seo_plan(topic, api_key, template_key, language, temperature, max_tokens, include_advanced_metrics):
        display_content_for_html_component = initial_placeholder_html
        current_markdown_for_state = latest_raw_markdown

        if output_from_generator.startswith("πŸ”„") or \
           output_from_generator.startswith("🧠") or \
           output_from_generator.startswith("πŸš€") or \
           output_from_generator.startswith("✨"):
            display_content_for_html_component = output_from_generator # Status messages as text
        elif output_from_generator.startswith("πŸ“ "):
            actual_markdown = output_from_generator[2:]
            latest_raw_markdown = actual_markdown
            current_markdown_for_state = actual_markdown
            display_content_for_html_component = "<p>πŸ“ Processing... please wait.</p>" + markdown.markdown(actual_markdown) # Show prefix, then HTML
        elif output_from_generator.startswith("⚠️"):
            display_content_for_html_component = output_from_generator # Error messages as text
            latest_raw_markdown = output_from_generator 
            current_markdown_for_state = output_from_generator
        else: # Final, complete markdown block
            latest_raw_markdown = output_from_generator
            current_markdown_for_state = output_from_generator
            display_content_for_html_component = markdown.markdown(output_from_generator)
        
        yield {
            outputs_map["seo_output"]: display_content_for_html_component,
            outputs_map["raw_seo_markdown_state"]: current_markdown_for_state
        }
    
    # Final yield to ensure state is correct
    if latest_raw_markdown:
        final_display = markdown.markdown(latest_raw_markdown) if not latest_raw_markdown.startswith("⚠️") else latest_raw_markdown
        yield {
            outputs_map["seo_output"]: final_display,
            outputs_map["raw_seo_markdown_state"]: latest_raw_markdown
        }

# Wrapper for non-streaming functions to convert MD to HTML and update states
def convert_md_to_html_for_output(fn_generating_markdown, *args):
    markdown_content = fn_generating_markdown(*args)
    html_content = ""
    if markdown_content.startswith("⚠️"):
        html_content = markdown_content # Pass error message as is
    else:
        html_content = markdown.markdown(markdown_content)
    # Returns a dictionary for multiple outputs
    return html_content, markdown_content


# Function to clear outputs
def clear_outputs_fn():
    return {
        inputs_map["topic_input"]: "",
        outputs_map["seo_output"]: "<p>Your comprehensive SEO plan will appear here...</p>",
        outputs_map["keyword_output"]: "<p>Your keyword research will appear here...</p>",
        outputs_map["content_ideas_output"]: "<p>Your content ideas will appear here...</p>",
        outputs_map["raw_seo_markdown_state"]: "",
        outputs_map["raw_keyword_markdown_state"]: "",
        outputs_map["raw_content_ideas_markdown_state"]: "",
        outputs_map["export_status"]: "",
        outputs_map["download_file"]: None,
        outputs_map["download_displayed_file"]: None,
    }


# Save API key to user's preferences
def save_api_key(api_key):
    if api_key.strip():
        with open(".env", "w") as f:
            f.write(f"GEMINI_API_KEY={api_key}")
        return "βœ… API key saved successfully!"
    return "⚠️ Please enter an API key to save"

# Enhanced theme
custom_theme = gr.themes.Soft(
    primary_hue="blue",
    secondary_hue="purple",
).set(
    body_text_color="#2d3748",
    block_title_text_weight="600",
    button_primary_background_fill="linear-gradient(90deg, #667eea 0%, #764ba2 100%)",
    button_primary_background_fill_hover="linear-gradient(90deg, #764ba2 0%, #667eea 100%)",
    button_primary_text_color="white",
    block_label_text_size="0.9rem",
    block_title_text_size="1.2rem"
)
# background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
# Main Gradio app with 6 organized sections
with gr.Blocks(title="Enhanced SEO Assistant", theme=custom_theme, css="""
    .main-container { max-width: 1200px; margin: 0 auto; }
    .section-header { background: #2563eb; color: white; padding: 15px; border-radius: 8px; margin: 20px 0 10px 0; text-align: center; font-weight: bold; }
    .feature-box { border: 2px solid #e2e8f0; border-radius: 8px; padding: 20px; margin: 10px 0; background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%); }
    .output-container { min-height: 400px; max-height: 800px; overflow-y: auto; border-left: 4px solid #667eea; padding: 20px; border-radius: 8px; margin: 10px 0; }
    .metrics-display { background: linear-gradient(135deg, #fed7d7 0%, #fbb6ce 100%); border-radius: 8px; padding: 15px; margin: 10px 0; }
""") as app:
    
    # Header
    gr.Markdown("""
    # πŸš€ Enhanced SEO Content Assistant
    ### AI-Powered Content Strategy for Food Bloggers & Content Creators
    Generate comprehensive SEO plans, keyword research, and content ideas using Google's Gemini 1.5 Pro.
    Rendered content is in HTML. You can download the styled export (from original Markdown) or the displayed HTML.
    """)

    # For mapping inputs/outputs in functions like clear_outputs_fn
    inputs_map = {}
    outputs_map = {}
    
    # ============== SECTION 1: API Configuration & Settings ==============
    with gr.Group():
        gr.HTML('<div class="section-header">πŸ”§ Section 1: API Configuration & Settings</div>')
        with gr.Row():
            with gr.Column(scale=2):
                api_key_input = gr.Textbox(label="πŸ”‘ Gemini API Key", placeholder="Enter your Google Gemini API key", value=os.getenv("GEMINI_API_KEY", ""), type="password")
                inputs_map["api_key_input"] = api_key_input
            with gr.Column(scale=1):
                save_api_btn = gr.Button("πŸ’Ύ Save Key", variant="secondary")
                api_status = gr.Textbox(label="Status", interactive=False, max_lines=1)
                outputs_map["api_status"] = api_status
        with gr.Row():
            with gr.Column():
                #gr.Markdown("### πŸŽ›οΈ Advanced Settings")
                temperature = gr.Slider(minimum=0.0, maximum=1.0, value=0.7, step=0.1, label="Temperature (Creativity)", info="Higher = more creative, Lower = more focused")
                inputs_map["temperature"] = temperature
            with gr.Column():
                max_tokens = gr.Slider(minimum=2000, maximum=8000, value=6000, step=500, label="Max Output Length", info="Maximum response length")
                inputs_map["max_tokens"] = max_tokens
            with gr.Column():
                include_advanced = gr.Checkbox(label="Include Advanced Metrics", value=True, info="Include technical SEO and content distribution strategies")
                inputs_map["include_advanced"] = include_advanced
    
    # ============== SECTION 2: Template & Language Selection ==============
    with gr.Group():
        gr.HTML('<div class="section-header">🎯 Section 2: Template & Language Selection</div>')
        with gr.Row():
            with gr.Column():
                template_dropdown = gr.Dropdown(choices=list(TEMPLATES.keys()), value="fermentation", label="🍽️ Content Template", info="Choose your food niche template")
                inputs_map["template_dropdown"] = template_dropdown
            with gr.Column():
                language_dropdown = gr.Dropdown(choices=list(LANGUAGES.keys()), value="English", label="🌐 Target Language", info="Optimize for specific language/region")
                inputs_map["language_dropdown"] = language_dropdown
        with gr.Accordion("πŸ“ Template Management", open=False):
            with gr.Row():
                with gr.Column():
                    custom_template_name = gr.Textbox(label="Template Name", placeholder="e.g., my_custom_template")
                    inputs_map["custom_template_name"] = custom_template_name
                    custom_template_content = gr.Textbox(label="Template Content", placeholder="Enter your custom template with {topic} placeholder", lines=10)
                    inputs_map["custom_template_content"] = custom_template_content
                    save_template_btn = gr.Button("πŸ’Ύ Save Custom Template")
                    template_status = gr.Textbox(label="Template Status", interactive=False)
                    outputs_map["template_status"] = template_status
                with gr.Column():
                    template_preview = gr.Textbox(label="Template Preview", placeholder="Select a template to preview", lines=10, interactive=False)
                    outputs_map["template_preview"] = template_preview
                    load_template_btn = gr.Button("πŸ‘€ Preview Selected Template")
    
    # ============== SECTION 3: Main SEO Plan Generation ==============
    with gr.Group():
        gr.HTML('<div class="section-header">✨ Section 3: SEO Plan Generation</div>')
        with gr.Row():
            with gr.Column(scale=1):
                topic_input = gr.Textbox(label="🎯 Your Content Topic", placeholder="e.g., Ultimate Guide to Homemade Kimchi", lines=3)
                inputs_map["topic_input"] = topic_input
                with gr.Row():
                    generate_btn = gr.Button("πŸš€ Generate SEO Plan", variant="primary", size="lg")
                    clear_btn = gr.Button("πŸ”„ Clear All", variant="secondary")
                gr.Examples(examples=["Beginner's Guide to Fermenting Vegetables at Home", "Perfect Sourdough Starter: Science and Technique", "Keto-Friendly Fermented Foods for Weight Loss"], inputs=topic_input, label="πŸ’‘ Example Topics")
            with gr.Column(scale=2):
                seo_output = gr.HTML(value="<p>Your comprehensive SEO plan will appear here...</p>", elem_classes=["output-container"])
                outputs_map["seo_output"] = seo_output
                raw_seo_markdown_state = gr.Textbox(visible=False, label="Raw SEO Markdown") # Hidden state
                outputs_map["raw_seo_markdown_state"] = raw_seo_markdown_state

    # ============== SECTION 4: Export & Download Options ==============
    with gr.Group():
        gr.HTML('<div class="section-header">πŸ“€ Section 4: Export & Download Options</div>')
        with gr.Row():
            with gr.Column():
                export_styled_html_btn = gr.Button("πŸ“„ Export Styled HTML (from Markdown)", variant="primary")
                download_displayed_html_btn = gr.Button("πŸ“„ Download Displayed HTML", variant="secondary")
                export_status = gr.Textbox(label="Export Status", interactive=False)
                outputs_map["export_status"] = export_status
            with gr.Column():
                download_file = gr.File(label="πŸ“₯ Download Styled Export File", interactive=False)
                outputs_map["download_file"] = download_file
                download_displayed_file = gr.File(label="πŸ“₯ Download Displayed HTML File", interactive=False) # New file component
                outputs_map["download_displayed_file"] = download_displayed_file
        gr.Markdown("""### πŸ“‹ Export Features:
        - **Styled HTML Export**: Professional, printable SEO plans from original Markdown.
        - **Displayed HTML Download**: Download the exact HTML rendered in the main output area.
        - **Template Information**: Includes template type and language used in styled export.
        - **Print-Friendly**: Styled export is optimized for PDF.
        - **Interactive Elements**: Clickable keywords in styled export.""")
    
    # ============== SECTION 5: Advanced SEO Tools ==============
    with gr.Group():
        gr.HTML('<div class="section-header">πŸ” Section 5: Advanced SEO Tools</div>')
        with gr.Tabs():
            with gr.Tab("🎯 Keyword Research"):
                with gr.Row():
                    keyword_topic = gr.Textbox(label="Topic for Keyword Research", placeholder="Enter topic for keyword analysis")
                    inputs_map["keyword_topic"] = keyword_topic
                    competition_level = gr.Dropdown(choices=["low", "medium", "high"], value="medium", label="Competition Level")
                    inputs_map["competition_level"] = competition_level
                keyword_research_btn = gr.Button("πŸ” Generate Keyword Report")
                keyword_output = gr.HTML(value="<p>Your keyword research will appear here...</p>", elem_classes=["output-container"])
                outputs_map["keyword_output"] = keyword_output
                raw_keyword_markdown_state = gr.Textbox(visible=False, label="Raw Keyword Markdown") # Hidden state
                outputs_map["raw_keyword_markdown_state"] = raw_keyword_markdown_state
            with gr.Tab("πŸ’‘ Content Ideas"):
                content_ideas_topic = gr.Textbox(label="Topic for Content Ideas", placeholder="Enter topic for content brainstorming")
                inputs_map["content_ideas_topic"] = content_ideas_topic
                content_ideas_btn = gr.Button("πŸ’‘ Generate Content Ideas")
                content_ideas_output = gr.HTML(value="<p>Your content ideas will appear here...</p>", elem_classes=["output-container"])
                outputs_map["content_ideas_output"] = content_ideas_output
                raw_content_ideas_markdown_state = gr.Textbox(visible=False, label="Raw Content Ideas Markdown") # Hidden state
                outputs_map["raw_content_ideas_markdown_state"] = raw_content_ideas_markdown_state
            with gr.Tab("πŸ“Š SEO Metrics"):
                gr.Markdown("""### πŸ“ˆ SEO Performance Metrics Included:
                - **Keyword Difficulty Analysis**: Competition assessment (1-100)
                - **Search Volume Estimates**: Monthly search predictions
                - **Content Length Recommendations**: Optimal word count
                - **Readability Targets**: Flesch-Kincaid score goals
                - **Technical SEO Checklist**: Page speed, schema markup
                - **Mobile Optimization**: Responsive design considerations""")
    
    # ============== SECTION 6: Language & Localization Settings ==============
    with gr.Group():
        gr.HTML('<div class="section-header">🌍 Section 6: Language & Localization Settings</div>')
        with gr.Accordion("πŸ”§ Language Settings Management", open=False):
            with gr.Row():
                with gr.Column():
                    lang_name = gr.Textbox(label="Language Name", placeholder="e.g., Portuguese")
                    inputs_map["lang_name"] = lang_name
                    search_engines = gr.Textbox(label="Search Engines", placeholder="Google, Bing, Yahoo (comma-separated)")
                    inputs_map["search_engines"] = search_engines
                    localization_tips = gr.Textbox(label="Localization Tips", placeholder="Regional considerations and market focus", lines=3)
                    inputs_map["localization_tips"] = localization_tips
                with gr.Column():
                    keyword_examples_txt = gr.Textbox(label="Keyword Examples", placeholder="Common keywords (comma-separated)", lines=2) # Renamed to avoid conflict
                    inputs_map["keyword_examples_txt"] = keyword_examples_txt
                    long_tail_patterns_txt = gr.Textbox(label="Long-tail Patterns", placeholder="Common long-tail patterns (comma-separated)", lines=2) # Renamed
                    inputs_map["long_tail_patterns_txt"] = long_tail_patterns_txt
                    question_keywords_txt = gr.Textbox(label="Question Keywords", placeholder="Common question words (comma-separated)", lines=2) # Renamed
                    inputs_map["question_keywords_txt"] = question_keywords_txt
            save_lang_btn = gr.Button("πŸ’Ύ Save Language Settings")
            lang_status = gr.Textbox(label="Language Settings Status", interactive=False)
            outputs_map["lang_status"] = lang_status
        gr.Markdown("""### πŸ—ΊοΈ Current Language Support:
        - **English**: US, UK, Canada, Australia markets
        - **Spanish**: Spain and Latin American markets
        - **French**: France, Belgium, Quebec, Switzerland
        - **German**: Germany, Austria, Switzerland
        - **Italian**: Italy with regional variations
        Add more languages using the settings panel above!""")

    # ============== EVENT HANDLERS ==============
    save_api_btn.click(fn=save_api_key, inputs=api_key_input, outputs=api_status)
    save_template_btn.click(fn=save_custom_template, inputs=[custom_template_name, custom_template_content], outputs=template_status)
    load_template_btn.click(fn=load_template_content, inputs=template_dropdown, outputs=template_preview)
    
    generate_btn.click(
        fn=stream_and_convert_seo_plan_wrapper,
        inputs=[topic_input, api_key_input, template_dropdown, language_dropdown, temperature, max_tokens, include_advanced],
        outputs=[seo_output, raw_seo_markdown_state], # seo_output (HTML), raw_seo_markdown_state (Markdown)
        show_progress="full"
    )
    
    export_styled_html_btn.click(
        fn=export_styled_html,
        inputs=[raw_seo_markdown_state, topic_input, template_dropdown, language_dropdown], # Use raw markdown state
        outputs=[export_status, download_file]
    )

    download_displayed_html_btn.click(
        fn=export_displayed_html,
        inputs=[seo_output, topic_input], # seo_output contains HTML
        outputs=[export_status, download_displayed_file] # Use new file component
    )
    
    def keyword_research_wrapper(topic, api_key, language, competition):
        html_out, md_out = convert_md_to_html_for_output(generate_keyword_research, topic, api_key, language, competition)
        return {keyword_output: html_out, raw_keyword_markdown_state: md_out}

    keyword_research_btn.click(
        fn=keyword_research_wrapper,
        inputs=[keyword_topic, api_key_input, language_dropdown, competition_level],
        outputs=[keyword_output, raw_keyword_markdown_state]
    )
    
    def content_ideas_wrapper(topic, api_key, template, language):
        html_out, md_out = convert_md_to_html_for_output(generate_content_ideas, topic, api_key, template, language)
        return {content_ideas_output: html_out, raw_content_ideas_markdown_state: md_out}

    content_ideas_btn.click(
        fn=content_ideas_wrapper,
        inputs=[content_ideas_topic, api_key_input, template_dropdown, language_dropdown],
        outputs=[content_ideas_output, raw_content_ideas_markdown_state]
    )
    
    save_lang_btn.click(
        fn=save_language_settings,
        inputs=[lang_name, search_engines, localization_tips, keyword_examples_txt, long_tail_patterns_txt, question_keywords_txt],
        outputs=lang_status
    )
    
    clear_btn.click(
        fn=clear_outputs_fn,
        outputs=list(outputs_map.values()) + [inputs_map["topic_input"]] # Clear relevant outputs and the main topic input
    )
    
    gr.Markdown("""---
    ## πŸš€ Enhanced Features Overview
    ### ✨ What's New:
    - **HTML Rendering**: Main content areas now render generated Markdown as HTML.
    - **Download Displayed HTML**: Button to download the HTML shown in the output area.
    - **Styled HTML Export**: Retained, uses original Markdown for professional, styled exports.
    - **6 Organized Sections**: Better UX with logical feature grouping.
    - **Custom Templates**: Create and manage your own templates.
    - **Multiple Food Niches**: Fermentation, Baking, Plant-Based, Keto, Mediterranean, Desserts.
    - **Advanced SEO Tools**: Keyword research and content idea generation.
    - **Multi-Language Support**: Optimize for different markets and languages.
    - **Enhanced Metrics**: Technical SEO, performance analysis, and content distribution.
    ### πŸ”— Useful Links:
    - [Get Gemini API Key](https://aistudio.google.com/)
    - [Gradio Documentation](https://gradio.app/docs/)
    - [SEO Best Practices](https://developers.google.com/search/docs)
    ### πŸ” Privacy & Security:
    Your API key is stored locally in a `.env` file (if you save it) and only used for Google AI services. No data is shared with third parties.""")

if __name__ == "__main__":
    print("πŸš€ Starting Enhanced SEO Assistant...")
    app.launch(
        #share=True, # Set to False if you don't want public sharing
        #debug=True,
        #show_error=True,
        #server_name="0.0.0.0",
        #server_port=7860,
        #quiet=False
    )