File size: 48,294 Bytes
ceb2258
c6164d9
1b40349
c6164d9
 
 
e78b3cb
 
 
 
 
 
1b40349
c6164d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b40349
ceb2258
c6164d9
 
 
 
 
 
 
 
 
 
e78b3cb
 
 
 
 
 
c6164d9
 
 
 
 
 
 
 
 
 
 
 
 
7d53291
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6164d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ceb2258
c6164d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b40349
e78b3cb
7d53291
 
e78b3cb
 
 
 
 
 
7d53291
e78b3cb
 
7d53291
e78b3cb
 
 
 
 
 
 
 
 
 
 
 
7d53291
e78b3cb
 
 
 
 
 
 
 
 
 
 
 
7d53291
e78b3cb
 
 
 
 
 
 
 
 
 
 
 
7d53291
e78b3cb
 
 
 
 
 
 
 
 
 
 
 
7d53291
e78b3cb
 
 
 
 
 
 
 
 
 
 
 
7d53291
e78b3cb
 
 
 
 
 
 
 
 
 
 
 
7d53291
e78b3cb
 
 
 
 
 
 
 
 
 
 
7d53291
e78b3cb
 
 
 
 
 
 
 
 
 
 
7d53291
e78b3cb
 
 
 
 
 
 
 
 
 
 
 
7d53291
e78b3cb
 
 
 
 
 
 
 
 
 
7d53291
e78b3cb
 
 
 
 
 
 
 
 
 
 
 
 
7d53291
 
c6164d9
 
 
 
7d53291
c6164d9
7d53291
c6164d9
 
 
 
7d53291
 
 
 
 
 
 
 
 
 
c6164d9
7d53291
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6164d9
7d53291
c6164d9
7d53291
 
 
 
 
c6164d9
7d53291
c6164d9
7d53291
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6164d9
7d53291
 
 
 
 
 
 
 
e78b3cb
7d53291
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6164d9
7d53291
 
 
 
 
c6164d9
 
 
7d53291
c6164d9
 
 
7d53291
 
e78b3cb
 
7d53291
e78b3cb
 
 
 
 
7d53291
e78b3cb
7d53291
 
e78b3cb
7d53291
e78b3cb
 
 
7d53291
 
 
e78b3cb
 
7d53291
e78b3cb
 
 
7d53291
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e78b3cb
7d53291
 
 
 
 
 
 
 
 
 
 
 
 
e78b3cb
 
 
 
7d53291
 
 
e78b3cb
 
7d53291
e78b3cb
 
 
7d53291
e78b3cb
7d53291
 
e78b3cb
 
 
 
7d53291
 
 
e78b3cb
 
7d53291
 
 
 
e78b3cb
 
7d53291
e78b3cb
7d53291
 
e78b3cb
 
 
 
7d53291
 
 
e78b3cb
 
7d53291
 
e78b3cb
 
7d53291
e78b3cb
 
7d53291
e78b3cb
 
 
7d53291
 
e78b3cb
7d53291
e78b3cb
 
 
 
 
 
c6164d9
 
 
 
e78b3cb
7d53291
e78b3cb
 
7d53291
 
 
 
e78b3cb
 
c6164d9
 
 
 
 
 
 
 
 
e78b3cb
 
 
 
 
 
c6164d9
 
 
 
 
 
 
1b40349
c6164d9
 
 
 
 
 
 
 
ceb2258
c6164d9
 
 
 
 
 
 
 
 
 
 
e78b3cb
 
 
 
c6164d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e78b3cb
 
c6164d9
7d53291
 
 
 
 
e78b3cb
 
 
 
 
 
 
 
 
 
 
 
 
c6164d9
 
e78b3cb
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
import gradio as gr
from fpdf import FPDF
import os
import tempfile
import re
import shutil
from datetime import datetime

# ===== New imports for PPT generation =====
from pptx import Presentation
from pptx.util import Inches, Pt
from pptx.enum.text import MSO_ANCHOR, PP_ALIGN

# ===== Import sentence-transformers for semantic similarity =====
from sentence_transformers import SentenceTransformer, util

# Load the semantic model once
model = SentenceTransformer("all-MiniLM-L6-v2")

# Define semantic categories with descriptions
categories = {
    "Food & Beverage": "Restaurants, cafes, food stalls, cloud kitchens, tiffin services, bakeries, catering.",
    "E-commerce": "Online stores, delivery apps, product marketplaces, digital selling platforms.",
    "Hospitality": "Hotels, homestays, guest houses, hostels, resorts, travel services.",
    "Pet Care": "Pet grooming, veterinary care, mobile vet vans, dog walking, animal boarding.",
    "Health & Fitness": "Gyms, yoga classes, personal training, physiotherapy, wellness programs.",
    "Education & Training": "Tutoring, courses, online schools, skill training, test preparation.",
    "Retail Automation": "Vending machines, smart kiosks, automated retail stores.",
    "Green & Sustainability": "Eco-friendly products, recycling, waste management, solar energy.",
    "Local Services": "Cleaning, handyman, repair, salon, on-demand home services.",
    "Technology / Software": "Apps, SaaS platforms, AI tools, fintech, blockchain services."
}

# Precompute embeddings for categories
category_embeddings = {
    cat: model.encode(desc, convert_to_tensor=True)
    for cat, desc in categories.items()
}

def semantic_category(idea):
    idea_emb = model.encode(idea, convert_to_tensor=True)
    scores = {cat: util.cos_sim(idea_emb, emb).item() for cat, emb in category_embeddings.items()}
    best_cat = max(scores, key=scores.get)
    confidence = round(scores[best_cat], 3)
    return best_cat, confidence

# -------------------- Text utilities --------------------
def normalize_for_pdf(text: str) -> str:
    text = (text.replace("β€”", "-")
                 .replace("–", "-")
                 .replace("β€’", "-")
                 .replace("βœ“", "")
                 .replace("βœ”", "")
                 .replace("βœ…", "")
                 .replace("❌", ""))
    try:
        text.encode("latin-1")
        return text
    except UnicodeEncodeError:
        return text.encode("latin-1", "ignore").decode("latin-1")

def has(text: str, *words):
    return any(w in text for w in words)

def extract_price_points(text: str):
    prices = re.findall(r"(β‚Ή\s*\d+[kKmM]?|Rs\.?\s*\d+[kKmM]?|\b\d{2,5}\b)", text)
    return ", ".join(prices[:5]) if prices else None

# -------------------- Budget analysis generator --------------------
def generate_budget_analysis(domain: str, idea: str):
    """Generate detailed budget analysis based on domain and idea"""

    main_domain = domain.split(" (")[0].strip()
    idea_lower = idea.lower()

    budget_data = {
        "Food & Beverage": {
            "startup_costs": {
                "Kitchen Setup/Equipment": "β‚Ή50,000 - β‚Ή2,00,000",
                "Initial Inventory": "β‚Ή15,000 - β‚Ή30,000",
                "Licenses (FSSAI, Local)": "β‚Ή5,000 - β‚Ή15,000",
                "Branding & Packaging": "β‚Ή10,000 - β‚Ή25,000",
                "Security Deposit": "β‚Ή20,000 - β‚Ή50,000"
            },
            "monthly_costs": {
                "Rent": "β‚Ή10,000 - β‚Ή40,000",
                "Raw Materials": "β‚Ή20,000 - β‚Ή60,000",
                "Staff Salary": "β‚Ή15,000 - β‚Ή45,000",
                "Utilities": "β‚Ή3,000 - β‚Ή8,000",
                "Marketing": "β‚Ή5,000 - β‚Ή15,000"
            },
            "revenue_projection": "β‚Ή1,00,000 - β‚Ή3,00,000/month",
            "break_even": "4-8 months",
            "total_investment": "β‚Ή1,00,000 - β‚Ή3,60,000"
        },

        "E-commerce": {
            "startup_costs": {
                "Website/Platform Setup": "β‚Ή25,000 - β‚Ή75,000",
                "Initial Inventory": "β‚Ή50,000 - β‚Ή2,00,000",
                "Photography & Content": "β‚Ή10,000 - β‚Ή20,000",
                "Legal & Registration": "β‚Ή10,000 - β‚Ή25,000",
                "Packaging Materials": "β‚Ή5,000 - β‚Ή15,000"
            },
            "monthly_costs": {
                "Platform Fees": "β‚Ή5,000 - β‚Ή20,000",
                "Inventory Replenishment": "β‚Ή40,000 - β‚Ή1,50,000",
                "Digital Marketing": "β‚Ή15,000 - β‚Ή50,000",
                "Fulfillment & Shipping": "β‚Ή10,000 - β‚Ή30,000",
                "Virtual Assistant": "β‚Ή8,000 - β‚Ή15,000"
            },
            "revenue_projection": "β‚Ή1,50,000 - β‚Ή5,00,000/month",
            "break_even": "6-12 months",
            "total_investment": "β‚Ή1,00,000 - β‚Ή3,35,000"
        },

        "Hospitality": {
            "startup_costs": {
                "Property Setup": "β‚Ή1,00,000 - β‚Ή5,00,000",
                "Furniture & Furnishing": "β‚Ή75,000 - β‚Ή2,00,000",
                "Licenses & Registration": "β‚Ή15,000 - β‚Ή35,000",
                "Initial Marketing": "β‚Ή20,000 - β‚Ή50,000",
                "Security Deposit": "β‚Ή50,000 - β‚Ή1,50,000"
            },
            "monthly_costs": {
                "Rent/EMI": "β‚Ή25,000 - β‚Ή80,000",
                "Housekeeping": "β‚Ή10,000 - β‚Ή25,000",
                "Utilities": "β‚Ή5,000 - β‚Ή15,000",
                "Platform Commission": "β‚Ή8,000 - β‚Ή20,000",
                "Maintenance": "β‚Ή5,000 - β‚Ή12,000"
            },
            "revenue_projection": "β‚Ή80,000 - β‚Ή2,50,000/month",
            "break_even": "8-15 months",
            "total_investment": "β‚Ή2,60,000 - β‚Ή9,35,000"
        },

        "Pet Care": {
            "startup_costs": {
                "Equipment & Tools": "β‚Ή30,000 - β‚Ή60,000",
                "Vehicle Setup": "β‚Ή50,000 - β‚Ή1,50,000",
                "Training & Certification": "β‚Ή15,000 - β‚Ή30,000",
                "Insurance": "β‚Ή10,000 - β‚Ή20,000",
                "Initial Marketing": "β‚Ή8,000 - β‚Ή15,000"
            },
            "monthly_costs": {
                "Fuel & Maintenance": "β‚Ή8,000 - β‚Ή15,000",
                "Supplies Replenishment": "β‚Ή5,000 - β‚Ή12,000",
                "Marketing": "β‚Ή5,000 - β‚Ή10,000",
                "Insurance Premium": "β‚Ή2,000 - β‚Ή4,000",
                "Helper Salary": "β‚Ή8,000 - β‚Ή15,000"
            },
            "revenue_projection": "β‚Ή60,000 - β‚Ή1,50,000/month",
            "break_even": "4-8 months",
            "total_investment": "β‚Ή1,13,000 - β‚Ή2,75,000"
        },

        "Technology / Software": {
            "startup_costs": {
                "Development Costs": "β‚Ή1,00,000 - β‚Ή5,00,000",
                "Cloud Infrastructure": "β‚Ή10,000 - β‚Ή25,000",
                "Legal & IP Protection": "β‚Ή20,000 - β‚Ή50,000",
                "Design & UX": "β‚Ή25,000 - β‚Ή75,000",
                "Testing & QA": "β‚Ή15,000 - β‚Ή40,000"
            },
            "monthly_costs": {
                "Server & Cloud Costs": "β‚Ή8,000 - β‚Ή25,000",
                "Development Team": "β‚Ή50,000 - β‚Ή2,00,000",
                "Marketing & Acquisition": "β‚Ή25,000 - β‚Ή1,00,000",
                "Support & Maintenance": "β‚Ή10,000 - β‚Ή30,000",
                "Third-party Services": "β‚Ή5,000 - β‚Ή15,000"
            },
            "revenue_projection": "β‚Ή1,00,000 - β‚Ή10,00,000/month",
            "break_even": "8-18 months",
            "total_investment": "β‚Ή1,70,000 - β‚Ή6,90,000"
        }
    }

    # Default budget for other domains
    default_budget = {
        "startup_costs": {
            "Equipment & Setup": "β‚Ή30,000 - β‚Ή80,000",
            "Initial Inventory/Supplies": "β‚Ή20,000 - β‚Ή50,000",
            "Legal & Registration": "β‚Ή8,000 - β‚Ή20,000",
            "Marketing Materials": "β‚Ή10,000 - β‚Ή25,000",
            "Working Capital": "β‚Ή25,000 - β‚Ή50,000"
        },
        "monthly_costs": {
            "Operational Expenses": "β‚Ή15,000 - β‚Ή35,000",
            "Staff/Helper Costs": "β‚Ή10,000 - β‚Ή25,000",
            "Marketing": "β‚Ή8,000 - β‚Ή20,000",
            "Utilities & Misc": "β‚Ή5,000 - β‚Ή12,000"
        },
        "revenue_projection": "β‚Ή80,000 - β‚Ή2,00,000/month",
        "break_even": "6-12 months",
        "total_investment": "β‚Ή93,000 - β‚Ή2,25,000"
    }

    budget_info = budget_data.get(main_domain, default_budget)

    # Adjust budget based on specific keywords in idea
    if "mobile" in idea_lower or "van" in idea_lower:
        budget_info = dict(budget_info)  # Create a copy
        if "startup_costs" in budget_info:
            budget_info["startup_costs"]["Vehicle/Mobile Setup"] = "β‚Ή50,000 - β‚Ή2,00,000"

    return budget_info

# -------------------- Dynamic suggestions generator --------------------
def generate_suggestions(domain, demand, audience, competitors, revenue, innovation, idea):
    """Generate dynamic suggestions based on the specific domain and idea characteristics"""

    suggestions = []
    main_domain = domain.split(" (")[0].strip()
    idea_lower = idea.lower()

    # Base validation suggestion - always relevant
    suggestions.append("1. Validate Early: Start with a 'concierge MVP' - manually deliver your service to 10 customers before building any technology or infrastructure.")

    # Domain-specific suggestions
    if main_domain == "Food & Beverage":
        if "temple" in idea_lower or "devotional" in idea_lower:
            suggestions.append("2. Festival Calendar Strategy: Plan inventory and staffing around religious festivals. Stock special prasad items and extended hours during peak devotional seasons.")
        elif "tech park" in idea_lower or "office" in idea_lower:
            suggestions.append("2. Corporate Partnerships: Negotiate with office complexes for exclusive food court rights or bulk lunch orders. Offer subscription meals for employees.")
        else:
            suggestions.append("2. Local Sourcing Edge: Partner directly with local farmers/suppliers to reduce costs by 15-20% while promoting 'farm-to-table' freshness.")

        suggestions.append("3. Quick Service Focus: Optimize for under 5-minute service time during peak hours. Pre-prepare popular items and use mobile ordering to reduce wait times.")

        if "delivery" in idea_lower:
            suggestions.append("4. Hyperlocal Delivery: Limit delivery radius to 3km for faster delivery and lower costs. Use WhatsApp ordering to avoid app development initially.")

    elif main_domain == "E-commerce":
        if "temple" in idea_lower or "pooja" in idea_lower:
            suggestions.append("2. Festival-Focused Inventory: Stock up 2 months before major festivals. Create festival-specific bundles and offer bulk discounts for family orders.")
            suggestions.append("3. Local Sourcing Advantage: Partner with local artisans and temple suppliers to offer authentic, region-specific religious items not available on Amazon/Flipkart.")
        else:
            suggestions.append("2. Niche Market Domination: Focus on a specific product category where you can become the #1 local supplier rather than competing broadly.")
            suggestions.append("3. Customer Service Differentiation: Offer same-day delivery, easy returns, and personal consultation calls - services big platforms can't match at local level.")

    elif main_domain == "Hospitality":
        if "pilgrim" in idea_lower or "temple" in idea_lower:
            suggestions.append("2. Package Deals: Create all-inclusive packages including accommodation, local guide, and temple visit arrangements. Partner with taxi services.")
            suggestions.append("3. Seasonal Pricing: Implement dynamic pricing for festival seasons and offer early bird discounts for off-season bookings.")
        else:
            suggestions.append("2. Experience Curation: Don't just offer accommodation - curate local experiences, food tours, or cultural activities that hotels can't provide.")
            suggestions.append("3. Long-stay Incentives: Offer weekly/monthly rates for business travelers or students. This provides steady cash flow and reduces booking overhead.")

    elif main_domain == "Pet Care":
        suggestions.append("2. Mobile Service Advantage: Offer at-home services when competitors require drop-offs. Create subscription packages for regular grooming/care.")
        suggestions.append("3. Trust Building: Provide real-time photo updates during service, background-verified staff, and emergency contact system for pet parents.")
        suggestions.append("4. Community Building: Create a local pet parent WhatsApp group for tips, emergency help, and word-of-mouth marketing.")

    elif main_domain == "Technology / Software":
        suggestions.append("2. No-Code MVP: Use tools like Bubble, Airtable, or Zapier to create your first version without hiring developers. Validate before investing in custom development.")
        suggestions.append("3. Local-First Strategy: Focus on solving hyper-local problems before expanding. Partner with local businesses as pilot customers.")
        suggestions.append("4. Freemium Model: Offer basic features free to build user base, then monetize with premium features or higher usage limits.")

    elif main_domain == "Health & Fitness":
        suggestions.append("2. Home Service Premium: Charge 2-3x more for at-home training compared to gym rates, but provide personalized attention and convenience.")
        suggestions.append("3. Corporate Wellness: Target companies for employee wellness programs. One corporate contract can replace 10+ individual clients.")
        suggestions.append("4. Results Documentation: Use before/after photos and progress tracking to build credibility and attract new clients through social proof.")

    # Location-specific suggestions
    if "mobile" in idea_lower or "van" in idea_lower:
        suggestions.append(f"{len(suggestions)+1}. Route Optimization: Plan daily routes to maximize stops while minimizing fuel costs. Use apps like Route4Me or Google My Maps for efficient planning.")

    # Competition-based suggestions
    if "unorganized" in competitors.lower() or "local" in competitors.lower():
        suggestions.append(f"{len(suggestions)+1}. Digital Advantage: Even basic digital presence (WhatsApp Business, Google My Business) can give you significant edge over traditional competitors.")

    # Revenue model suggestions
    if "subscription" in revenue.lower():
        suggestions.append(f"{len(suggestions)+1}. Subscription Psychology: Offer annual plans with 2-month discount. Monthly subscribers often churn, but annual payments improve cash flow and retention.")

    # Final strategic suggestion based on demand level
    if "High" in demand:
        suggestions.append(f"{len(suggestions)+1}. Scale Preparation: High demand means focus on operational efficiency from day 1. Document all processes to enable quick team expansion.")
    elif "Moderate" in demand:
        suggestions.append(f"{len(suggestions)+1}. Community Building: Moderate demand requires strong word-of-mouth. Focus on exceptional service to your first 50 customers to create advocates.")
    else:
        suggestions.append(f"{len(suggestions)+1}. Pivot Readiness: Test multiple variations of your service offering quickly. Low initial demand may require repositioning your value proposition.")

    # Ensure we don't exceed reasonable length
    return suggestions[:6]

# -------------------- Idea analysis --------------------
def classify_and_analyze(idea: str):
    t = idea.lower()
    near_temples = has(t, "temple", "mandir", "pilgrim", "pooja", "devotional")
    near_it_parks = has(t, "it park", "tech park", "office", "corporate", "campus", "hitec", "hitech")
    metro_transit = has(t, "metro", "railway", "bus station", "airport", "transit", "station")
    local_delivery = has(t, "deliver", "delivery", "on-demand", "doorstep", "hyperlocal", "last mile")

    is_food = has(t, "tiffin", "meal", "restaurant", "cafe", "coffee", "tea", "cloud kitchen", "snacks", "veg", "vegetarian")
    is_vending = has(t, "vending machine", "vending", "kiosk")
    is_ecom = has(t, "online store", "ecommerce", "marketplace", "shop")
    is_hospitality = has(t, "homestay", "stay", "hostel", "guest house", "lodge")
    is_souvenir = has(t, "souvenir", "prasad", "gift", "religious items", "pooja items")
    is_services = has(t, "services", "local services", "handyman", "utility", "cleaning", "repair")

    # Keyword-based domain classification
    if is_food and near_it_parks:
        domain = "Food & Beverage (workforce-focused)"
    elif is_food and near_temples:
        domain = "Food & Beverage (religious tourism)"
    elif is_food:
        domain = "Food & Beverage"
    elif is_vending and metro_transit:
        domain = "Retail Automation (vending at transit)"
    elif is_vending:
        domain = "Retail Automation (vending)"
    elif is_hospitality and near_temples:
        domain = "Hospitality (religious tourism)"
    elif is_hospitality:
        domain = "Hospitality"
    elif is_ecom and near_temples:
        domain = "E-commerce (devotional goods / hyperlocal)"
    elif is_ecom:
        domain = "E-commerce"
    elif is_souvenir and near_temples:
        domain = "Retail (souvenirs for pilgrims)"
    elif is_services or local_delivery:
        domain = "Local Services / Hyperlocal Delivery"
    else:
        domain = "General Local Commerce / Services"

    semantic_conf = 0
    if domain == "General Local Commerce / Services":
        sem_domain, conf = semantic_category(idea)
        semantic_conf = conf
        domain = f"{sem_domain} (semantic match {conf})"

    # Demand
    if is_food and (near_it_parks or metro_transit):
        demand = "High - strong weekday footfall; peaks at commute and lunch times."
    elif is_food and near_temples:
        demand = "Moderate to High - weekends/festivals spike; morning and evening peaks."
    elif is_vending and metro_transit:
        demand = "Moderate - permit dependent; strong impulse buys with right placement."
    elif is_hospitality and near_temples:
        demand = "High in season and festivals, moderate otherwise."
    elif is_ecom and near_temples:
        demand = "Moderate - niche but loyal; festival boosts."
    else:
        demand = "Moderate - validate via small test."

    # Audience
    if near_it_parks:
        audience = "Office workers, contractors, security staff, delivery riders."
    elif near_temples:
        audience = "Pilgrims, families, local devotees, tour groups."
    elif metro_transit:
        audience = "Daily commuters, students, travelers."
    else:
        audience = "Local residents within 2-5 km radius; nearby early adopters."

    # Competitors
    if is_food:
        competitors = "Cloud kitchens, canteens, tea/coffee stalls, Swiggy/Zomato vendors."
    elif is_vending:
        competitors = "Kiosks, convenience stores; few automated options."
    elif is_hospitality:
        competitors = "Budget hotels, homestays, lodges."
    elif is_ecom:
        competitors = "Local kirana/pooja shops, Amazon/Flipkart resellers."
    else:
        competitors = "Unorganized local players; compete on convenience and trust."

    # Revenue
    price_hint = extract_price_points(t)
    if is_food:
        revenue = "Per-item, combos; subscriptions; corporate tie-ups."
    elif is_vending:
        revenue = "Per-transaction; convenience premium; ads on machines."
    elif is_hospitality:
        revenue = "Nightly rates; surge pricing in festivals."
    elif is_ecom or local_delivery:
        revenue = "Product margin + delivery fee; festive bundles."
    else:
        revenue = "Service fees, bundles, memberships."
    if price_hint:
        revenue += f" Detected price hints: {price_hint}."

    # Features
    features = []
    if is_food:
        features += ["Simple menu", "Under 5 min service", "Clean packaging", "Digital payments"]
    if is_vending:
        features += ["Cashless", "24/7 access", "Live stock display", "Quick purchase"]
    if is_ecom or local_delivery:
        features += ["3-step ordering", "Same-day delivery", "Clear pricing", "Order tracking"]
    if is_hospitality:
        features += ["Clean rooms", "Local guide", "Flexible check-in", "Easy booking"]
    if near_temples:
        features += ["Festival-ready packs", "Location-aware directions"]
    if near_it_parks:
        features += ["Office timings", "Bulk orders"]
    if not features:
        features = ["Simple onboarding", "Fast support", "Mobile-friendly experience"]

    # Innovation
    if is_vending:
        innovation = "Smart inventory, remote monitoring."
    elif is_food and near_it_parks:
        innovation = "Pre-order pickups, corporate subscriptions."
    elif is_food and near_temples:
        innovation = "Queue tokens, hygienic prasad packs."
    elif is_hospitality:
        innovation = "Curated itineraries, verified guides."
    elif is_ecom:
        innovation = "Local sourcing, festival logistics."
    else:
        innovation = "Digitize discovery, bookings, feedback."

    # ===== Improved SCORING =====
    base_score_map = {
        "Food & Beverage": 7.5,
        "E-commerce": 7.2,
        "Hospitality": 6.8,
        "Pet Care": 7.0,
        "Health & Fitness": 7.4,
        "Education & Training": 7.6,
        "Retail Automation": 7.1,
        "Green & Sustainability": 7.8,
        "Local Services": 6.9,
        "Technology / Software": 8.0
    }

    if semantic_conf > 0:
        base_cat = domain.split(" (semantic")[0]
        score = base_score_map.get(base_cat, 7.0) + (semantic_conf - 0.5) * 3
    else:
        score = 7.0

    if is_food: score += 0.5
    if near_it_parks: score += 0.3
    if near_temples: score += 0.2
    if is_vending: score -= 0.3
    if is_hospitality: score -= 0.1

    score = round(max(1.0, min(10.0, score)), 1)

    analysis_lines = [
        f"Domain: {domain}",
        f"Market Demand: {demand}",
        f"Target Audience: {audience}",
        f"Competitor Analysis: {competitors}",
        f"Revenue Model: {revenue}",
        f"Innovation Potential: {innovation}",
        f"Build Possibility Score: {score}/10"
    ]

    # Call the updated function to generate dynamic suggestions
    suggestions = generate_suggestions(domain, demand, audience, competitors, revenue, innovation, idea)

    return analysis_lines, features[:6], "; ".join(features[:6]), suggestions, domain

# -------------------- Domain-specific implementation plans --------------------
def implementation_plan(idea: str, domain: str):
    """Generate domain-specific implementation plans"""

    # Extract main domain category
    main_domain = domain.split(" (")[0].strip()

    if main_domain == "Food & Beverage":
        return [
            "Week 1-2: Menu Planning & Licensing - Define 3-5 signature items, get FSSAI license, identify suppliers.",
            "Week 3: Location Scouting - Secure kitchen space/stall, negotiate rent, ensure water/electricity access.",
            "Week 4: Setup Basic Operations - Install cooking equipment, create simple POS system, design basic packaging.",
            "Week 5: Soft Launch - Start with friends/family, gather feedback, refine recipes and service time.",
            "Week 6-7: Marketing Push - Create social media presence, distribute flyers, partner with local offices/groups.",
            "Week 8-9: Scale Operations - Implement online ordering (WhatsApp/simple app), add delivery if viable.",
            "Month 3: Optimize & Expand - Track popular items, reduce waste, consider catering services or second location.",
            "Month 4-6: Build Loyalty - Introduce membership discounts, bulk order deals, seasonal menu updates.",
            "Month 6+: Growth Strategy - Explore franchising, corporate tie-ups, or expanding to related food categories."
        ]

    elif main_domain == "E-commerce":
        return [
            "Week 1: Market Research - Validate product demand, analyze competitors, define unique value proposition.",
            "Week 2: Product Sourcing - Identify reliable suppliers, negotiate terms, order initial inventory (start small).",
            "Week 3-4: Platform Setup - Create website/use existing marketplace (Amazon, Flipkart), setup payment gateway.",
            "Week 5: Photography & Listings - Professional product photos, compelling descriptions, competitive pricing.",
            "Week 6-7: Soft Launch - List products, test ordering process, fulfill first orders manually to ensure quality.",
            "Week 8-10: Marketing & SEO - Social media campaigns, Google Ads, influencer partnerships, optimize for search.",
            "Month 3: Automation & Scaling - Implement inventory management, consider fulfillment services, expand product range.",
            "Month 4-6: Customer Retention - Email marketing, loyalty programs, customer service optimization, reviews management.",
            "Month 6+: Advanced Growth - Data analytics, international expansion, private labeling, or marketplace partnerships."
        ]

    elif main_domain == "Hospitality":
        return [
            "Week 1-2: Property & Legal - Secure property lease, get tourism/hospitality licenses, fire safety clearance.",
            "Week 3-4: Setup & Furnishing - Basic furniture, clean bedding, bathroom essentials, Wi-Fi setup.",
            "Week 5: Booking Platform - List on Airbnb/Booking.com, create simple website, setup online payment.",
            "Week 6: Service Standards - Define check-in/out process, cleaning protocols, local area guides.",
            "Week 7-8: Soft Launch - Host friends/family, gather feedback, refine processes, take quality photos.",
            "Week 9-10: Marketing Push - Social media presence, local tourism partnerships, guest review optimization.",
            "Month 3: Operational Excellence - Streamline housekeeping, 24/7 support system, guest experience improvements.",
            "Month 4-6: Expand Services - Local tour packages, airport transfers, meal services, seasonal promotions.",
            "Month 6+: Scale or Premium - Additional properties, premium services, corporate bookings, or unique experiences."
        ]

    elif main_domain == "Pet Care":
        return [
            "Week 1-2: Skills & Certification - Get pet care certification, first aid training, insurance coverage.",
            "Week 3: Equipment & Supplies - Purchase grooming tools, transportation setup, create service kits.",
            "Week 4: Service Menu - Define services (grooming, walking, sitting), create pricing structure.",
            "Week 5-6: Legal & Marketing - Business registration, create flyers, social media profiles, local vet partnerships.",
            "Week 7-8: Pilot Testing - Offer services to friends/family pets, gather testimonials, refine processes.",
            "Week 9-12: Customer Acquisition - Door-to-door marketing, online presence, pet community engagement.",
            "Month 3: Service Excellence - Develop standard operating procedures, emergency protocols, client communication system.",
            "Month 4-6: Business Growth - Hire additional staff, expand service area, introduce premium services.",
            "Month 6+: Scale Operations - Multiple service teams, pet product sales, training programs, or franchise model."
        ]

    elif main_domain == "Health & Fitness":
        return [
            "Week 1-2: Certification & Planning - Get fitness certifications, define target audience, create program curriculum.",
            "Week 3: Space & Equipment - Secure training space/gym partnership, buy basic equipment, ensure safety measures.",
            "Week 4: Program Development - Design workout plans, nutrition guides, progress tracking systems.",
            "Week 5-6: Marketing Materials - Create promotional content, before/after testimonials, pricing packages.",
            "Week 7-8: Soft Launch - Train friends/family for free, gather feedback, refine programs.",
            "Week 9-12: Client Acquisition - Social media marketing, local partnerships, referral programs, free trial sessions.",
            "Month 3: Service Optimization - Track client progress, improve retention rates, add group classes.",
            "Month 4-6: Expand Offerings - Online coaching, nutrition consultation, corporate wellness programs.",
            "Month 6+: Scale Business - Hire trainers, multiple locations, fitness app development, or online course creation."
        ]

    elif main_domain == "Education & Training":
        return [
            "Week 1-2: Curriculum Design - Define learning objectives, create course materials, assessment methods.",
            "Week 3: Platform Setup - Choose teaching platform (Zoom, classroom), create learning management system.",
            "Week 4: Marketing Materials - Course brochures, demo videos, testimonials, pricing structure.",
            "Week 5-6: Pilot Program - Run free/discounted sessions, gather feedback, refine teaching methods.",
            "Week 7-8: Student Acquisition - Social media marketing, educational partnerships, word-of-mouth referrals.",
            "Week 9-12: Course Delivery - Maintain quality, track student progress, provide personalized support.",
            "Month 3: Program Enhancement - Add advanced modules, practical projects, certification programs.",
            "Month 4-6: Scale Offerings - Multiple course levels, corporate training, online self-paced options.",
            "Month 6+: Business Expansion - Hire instructors, franchise model, educational technology development."
        ]

    elif main_domain == "Retail Automation":
        return [
            "Week 1-3: Market Research - Identify high-traffic locations, study foot patterns, negotiate placement permits.",
            "Week 4-6: Machine Procurement - Source vending machines, customize for products, install payment systems.",
            "Week 7: Location Setup - Install machines, ensure power/connectivity, create attractive signage.",
            "Week 8-10: Product Testing - Stock popular items, monitor sales patterns, adjust inventory mix.",
            "Week 11-12: Operations Optimization - Establish restocking schedule, remote monitoring system, maintenance protocols.",
            "Month 3: Performance Analysis - Track sales data, customer preferences, optimize product placement.",
            "Month 4-6: Expand Network - Add more machines in successful locations, explore new product categories.",
            "Month 6+: Advanced Features - Implement AI-based inventory, digital advertising, cashless payment upgrades."
        ]

    elif main_domain == "Green & Sustainability":
        return [
            "Week 1-2: Impact Assessment - Define environmental problem, research sustainable solutions, identify target market.",
            "Week 3-4: Product/Service Development - Source eco-friendly materials, design sustainable processes, get certifications.",
            "Week 5: Pilot Testing - Create prototypes/test services, gather user feedback, measure environmental impact.",
            "Week 6-8: Brand Building - Create compelling sustainability story, educational content, community partnerships.",
            "Week 9-12: Market Launch - Target environmentally conscious consumers, premium pricing for quality.",
            "Month 3: Community Engagement - Partner with environmental organizations, schools, corporate CSR programs.",
            "Month 4-6: Scale Impact - Expand product range, improve processes, measure and report environmental benefits.",
            "Month 6+: Systematic Change - Influence supply chains, policy advocacy, create industry standards."
        ]

    elif main_domain == "Local Services":
        return [
            "Week 1-2: Service Definition - List specific services, create service packages, define service area.",
            "Week 3: Equipment & Supplies - Purchase necessary tools, create mobile service kit, get vehicle if needed.",
            "Week 4: Pricing & Scheduling - Create transparent pricing, booking system, availability calendar.",
            "Week 5-6: Local Marketing - Door-to-door flyers, local Facebook groups, partner with real estate agents.",
            "Week 7-8: Service Delivery - Focus on quality, punctuality, customer satisfaction, gather reviews.",
            "Week 9-12: Customer Base Building - Referral programs, repeat customer discounts, seasonal service packages.",
            "Month 3: Operational Excellence - Streamline processes, invest in better tools, hire additional help if needed.",
            "Month 4-6: Service Expansion - Add complementary services, emergency services, maintenance packages.",
            "Month 6+: Business Growth - Multiple service teams, commercial clients, franchise opportunities."
        ]

    elif main_domain == "Technology / Software":
        return [
            "Week 1-3: Product Planning - Define user problems, create feature list, design user experience wireframes.",
            "Week 4-8: MVP Development - Build minimum viable product, focus on core functionality, ensure basic security.",
            "Week 9-10: Beta Testing - Release to limited users, gather feedback, fix critical bugs.",
            "Week 11-12: Launch Preparation - App store optimization, landing page, user onboarding flow.",
            "Month 3: User Acquisition - Digital marketing, product hunt launch, influencer outreach, content marketing.",
            "Month 4-6: Product Iteration - Analyze user behavior, add features based on feedback, improve retention.",
            "Month 6+: Scale & Monetize - Implement revenue model, scale infrastructure, explore partnerships or funding."
        ]

    else:  # Default/General plan
        return [
            "Week 1-2: Define your offer - 3-5 best-sellers and clear pricing.",
            "Week 3: Run a 1-week pilot with a basic landing page or local test.",
            "Week 4: Setup MVP - branding, UPI/QR payments, simple inventory in a spreadsheet.",
            "Week 5-6: Choose 1-2 locations and secure local permissions.",
            "Week 7-8: Optimize operations for 5-minute service time.",
            "Week 9-10: Bundle pricing during peak hours or festivals.",
            "Week 11-12: Promote using signage, WhatsApp lists, and Google Maps.",
            "Month 3: Track key metrics (orders/day, repeat rate) and iterate weekly.",
            "Month 6+: Scale to second location once you hit 30% repeat customers for 3 weeks."
        ]

# -------------------- Enhanced PDF generator with budget analysis --------------------
def generate_pdf(idea, analysis_lines, features, impl_steps, suggestions, domain):
    pdf = FPDF()
    pdf.set_auto_page_break(auto=True, margin=15)
    pdf.add_page()

    # Title
    pdf.set_font("Arial", "B", 16)
    pdf.cell(0, 10, txt=normalize_for_pdf("Startup Idea Analysis Report"), ln=True, align="C")
    pdf.set_font("Arial", "", 12)
    pdf.ln(4)
    pdf.multi_cell(0, 8, txt=normalize_for_pdf(f"Idea: {idea}"))
    pdf.ln(2)

    # Date
    pdf.set_font("Arial", "I", 10)
    pdf.cell(0, 6, txt=normalize_for_pdf(f"Generated on: {datetime.now().strftime('%B %d, %Y')}"), ln=True, align="R")
    pdf.ln(4)

    # Analysis Section
    pdf.set_font("Arial", "B", 14)
    pdf.cell(0, 8, txt=normalize_for_pdf("Business Analysis"), ln=True)
    pdf.set_font("Arial", "", 11)
    for idx, line in enumerate(analysis_lines, start=1):
        pdf.multi_cell(0, 6, txt=normalize_for_pdf(f"{idx}. {line}"))
        pdf.ln(1)

    # Budget Analysis Section
    pdf.ln(3)
    pdf.set_font("Arial", "B", 14)
    pdf.cell(0, 8, txt=normalize_for_pdf("Budget Analysis"), ln=True)

    budget_info = generate_budget_analysis(domain, idea)

    # Startup Costs
    pdf.set_font("Arial", "B", 12)
    pdf.cell(0, 7, txt=normalize_for_pdf("Initial Investment Required:"), ln=True)
    pdf.set_font("Arial", "", 11)
    for item, cost in budget_info["startup_costs"].items():
        pdf.multi_cell(0, 5, txt=normalize_for_pdf(f"β€’ {item}: {cost}"))

    # Monthly Costs
    pdf.ln(2)
    pdf.set_font("Arial", "B", 12)
    pdf.cell(0, 7, txt=normalize_for_pdf("Monthly Operating Costs:"), ln=True)
    pdf.set_font("Arial", "", 11)
    for item, cost in budget_info["monthly_costs"].items():
        pdf.multi_cell(0, 5, txt=normalize_for_pdf(f"β€’ {item}: {cost}"))

    # Financial Projections
    pdf.ln(2)
    pdf.set_font("Arial", "B", 12)
    pdf.cell(0, 7, txt=normalize_for_pdf("Financial Projections:"), ln=True)
    pdf.set_font("Arial", "", 11)
    pdf.multi_cell(0, 5, txt=normalize_for_pdf(f"β€’ Expected Revenue: {budget_info['revenue_projection']}"))
    pdf.multi_cell(0, 5, txt=normalize_for_pdf(f"β€’ Break-even Timeline: {budget_info['break_even']}"))
    pdf.multi_cell(0, 5, txt=normalize_for_pdf(f"β€’ Total Investment Range: {budget_info['total_investment']}"))

    # Key Features
    pdf.ln(4)
    pdf.set_font("Arial", "B", 14)
    pdf.cell(0, 8, txt=normalize_for_pdf("Essential Features"), ln=True)
    pdf.set_font("Arial", "", 11)
    for f in features:
        pdf.multi_cell(0, 6, txt=normalize_for_pdf(f"β€’ {f}"))

    # Implementation Plan
    pdf.ln(3)
    pdf.set_font("Arial", "B", 14)
    pdf.cell(0, 8, txt=normalize_for_pdf("Detailed Implementation Roadmap"), ln=True)
    pdf.set_font("Arial", "", 11)
    for i, step in enumerate(impl_steps, start=1):
        pdf.multi_cell(0, 6, txt=normalize_for_pdf(f"{i}. {step}"))
        pdf.ln(1)

    # Strategic Suggestions
    pdf.ln(3)
    pdf.set_font("Arial", "B", 14)
    pdf.cell(0, 8, txt=normalize_for_pdf("Strategic Recommendations"), ln=True)
    pdf.set_font("Arial", "", 11)
    for s in suggestions:
        pdf.multi_cell(0, 6, txt=normalize_for_pdf(s))
        pdf.ln(1)

    # Risk Assessment
    pdf.ln(3)
    pdf.set_font("Arial", "B", 14)
    pdf.cell(0, 8, txt=normalize_for_pdf("Key Risk Factors & Mitigation"), ln=True)
    pdf.set_font("Arial", "", 11)

    # Generate domain-specific risks
    main_domain = domain.split(" (")[0].strip()
    risks = {
        "Food & Beverage": [
            "β€’ Health regulations compliance - Obtain all required licenses before operations",
            "β€’ Food safety and quality control - Implement strict hygiene protocols",
            "β€’ Seasonal demand fluctuations - Diversify menu and target multiple customer segments"
        ],
        "E-commerce": [
            "β€’ High customer acquisition costs - Focus on organic growth and referrals initially",
            "β€’ Inventory management challenges - Start with limited SKUs and pre-orders",
            "β€’ Platform dependency risks - Build direct customer relationships through email/WhatsApp"
        ],
        "Technology / Software": [
            "β€’ Technical development delays - Use no-code solutions initially, hire experienced developers",
            "β€’ User adoption challenges - Focus on solving a real pain point with simple UX",
            "β€’ Competition from established players - Target niche market segments first"
        ]
    }

    default_risks = [
        "β€’ Market validation failure - Start with small pilot before full investment",
        "β€’ Cash flow management - Maintain 3-6 months operating expenses as buffer",
        "β€’ Competition response - Focus on unique value proposition and customer service excellence"
    ]

    domain_risks = risks.get(main_domain, default_risks)
    for risk in domain_risks:
        pdf.multi_cell(0, 6, txt=normalize_for_pdf(risk))

    # Save PDF
    fd, path = tempfile.mkstemp(suffix=".pdf")
    os.close(fd)
    pdf.output(path)
    output_path = os.path.join(tempfile.gettempdir(), f"Startup_Analysis_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf")
    shutil.copy(path, output_path)
    return output_path

# -------------------- Enhanced PPT generator --------------------
def generate_ppt(idea, analysis_lines, features, impl_steps, suggestions, domain):
    try:
        prs = Presentation()

        # --- Slide 1: Title Slide ---
        title_slide_layout = prs.slide_layouts[0]
        slide = prs.slides.add_slide(title_slide_layout)
        title = slide.shapes.title
        subtitle = slide.placeholders[1]

        title.text = "Startup Idea Analysis"
        subtitle.text = f"Idea: {idea}\nGenerated: {datetime.now().strftime('%B %d, %Y')}"

        # --- Slide 2: Key Analysis ---
        analysis_slide_layout = prs.slide_layouts[1]
        slide = prs.slides.add_slide(analysis_slide_layout)
        title = slide.shapes.title
        body = slide.shapes.placeholders[1]

        title.text = "Business Analysis Overview"

        tf = body.text_frame
        tf.clear()

        for line in analysis_lines:
            p = tf.add_paragraph()
            p.text = line
            p.font.size = Pt(14)
            p.level = 0

        # --- Slide 3: Budget Analysis ---
        budget_slide_layout = prs.slide_layouts[1]
        slide = prs.slides.add_slide(budget_slide_layout)
        title = slide.shapes.title
        body = slide.shapes.placeholders[1]

        title.text = "Financial Requirements"

        tf = body.text_frame
        tf.clear()

        budget_info = generate_budget_analysis(domain, idea)

        # Add startup costs
        p = tf.add_paragraph()
        p.text = "Initial Investment:"
        p.font.size = Pt(16)
        p.font.bold = True
        p.level = 0

        for item, cost in list(budget_info["startup_costs"].items())[:4]:  # Limit to first 4 items
            p = tf.add_paragraph()
            p.text = f"{item}: {cost}"
            p.font.size = Pt(12)
            p.level = 1

        # Add key financial metrics
        p = tf.add_paragraph()
        p.text = f"Expected Revenue: {budget_info['revenue_projection']}"
        p.font.size = Pt(14)
        p.level = 0

        p = tf.add_paragraph()
        p.text = f"Break-even: {budget_info['break_even']}"
        p.font.size = Pt(14)
        p.level = 0

        # --- Slide 4: Key Features ---
        features_slide_layout = prs.slide_layouts[1]
        slide = prs.slides.add_slide(features_slide_layout)
        title = slide.shapes.title
        body = slide.shapes.placeholders[1]

        title.text = "Essential Features"

        tf = body.text_frame
        tf.clear()

        for feature in features:
            p = tf.add_paragraph()
            p.text = feature
            p.font.size = Pt(14)
            p.level = 0

        # --- Slide 5: Implementation Timeline ---
        impl_slide_layout = prs.slide_layouts[1]
        slide = prs.slides.add_slide(impl_slide_layout)
        title = slide.shapes.title
        body = slide.shapes.placeholders[1]

        title.text = "Implementation Roadmap"

        tf = body.text_frame
        tf.clear()

        # Show only key milestones to avoid overcrowding
        key_steps = impl_steps[:6]  # First 6 steps
        for i, step in enumerate(key_steps, start=1):
            p = tf.add_paragraph()
            p.text = f"{i}. {step}"
            p.font.size = Pt(11)
            p.level = 0

        # --- Slide 6: Strategic Recommendations ---
        suggestions_slide_layout = prs.slide_layouts[1]
        slide = prs.slides.add_slide(suggestions_slide_layout)
        title = slide.shapes.title
        body = slide.shapes.placeholders[1]

        title.text = "Strategic Recommendations"

        tf = body.text_frame
        tf.clear()

        for s in suggestions[:5]:  # Limit to 5 suggestions
            p = tf.add_paragraph()
            p.text = s
            p.font.size = Pt(12)
            p.level = 0

        # Save the presentation
        fd, path = tempfile.mkstemp(suffix=".pptx")
        os.close(fd)
        prs.save(path)

        output_path = os.path.join(tempfile.gettempdir(), f"Startup_Presentation_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pptx")
        shutil.copy(path, output_path)

        return output_path

    except Exception as e:
        print(f"An error occurred while generating the PPT: {e}")
        return None

# -------------------- Backend glue --------------------
def validate_idea(idea):
    if not idea.strip():
        errors = ["Please enter or select a valid startup idea."] * 7
        return (*errors, "Add 3-6 simple features that anyone can understand.", "", None, None)

    analysis_lines, features, features_text, suggestions, domain = classify_and_analyze(idea)
    impl_steps = implementation_plan(idea, domain)
    pdf_path = generate_pdf(idea, analysis_lines, features, impl_steps, suggestions, domain)
    ppt_path = generate_ppt(idea, analysis_lines, features, impl_steps, suggestions, domain)

    suggestions_text = "\n".join(suggestions)

    return (*analysis_lines, features_text, suggestions_text, pdf_path, ppt_path)

# -------------------- Samples --------------------
sample_ideas = [
    "Vegetarian restaurant near popular temples and devotional sites.",
    "Online store delivering milk, vegetables, and pooja items.",
    "Mobile coffee stall near tech parks for working professionals.",
    "Eco-friendly tiffin delivery using steel boxes near IT hubs.",
    "Book vending machines at metro stations and spiritual fairs.",
    "Local homestays for pilgrims with devotional guides and maps.",
    "Temple-based souvenir shops with online delivery.",
    "Pet grooming and care services in residential areas.",
    "Home fitness training and nutrition coaching.",
    "Online coding bootcamp for working professionals.",
    "Solar panel installation and maintenance services.",
    "Mobile handyman and repair services app"
]

# -------------------- UI --------------------
with gr.Blocks(css="""
.gradio-container {
    background-image: url('https://media.istockphoto.com/id/1439748746/video/beautiful-gold-rain-centered-loopable-background-animation-glitter-and-light-beams-christmas.jpg?b=1&s=640x640&k=20&c=WaO9c87ruc2pWqHopzUlFGwYnjKWq0QKEU03JaF8eN8=');
    background-size: center;
    font-family: 'Segoe UI', sans-serif;
    color: white;
}
.container {
    background: rgba(0, 0, 0, 0.75);
    padding: 30px;
    border-radius: 15px;
    max-width: 780px;
    margin: auto;
}
.gr-button {
    background-color: #2ecc71 !important;
    color: white !important;
}
textarea, input, .gr-textbox textarea, .gr-textbox input {
    color: #111 !important;
    background: #fff !important;
}
label, .gr-form, .gr-block .label {
    color: #fff !important;
}
.gr-html h1 {
    color: white !important;
    font-weight: bold !important;
}
""") as demo:

    with gr.Column(elem_classes="container"):
        gr.HTML("<h1 style='text-align:center;'>Idealyze β€” Validate Your Startup Idea</h1>")
        idea_input = gr.Textbox(
            label="Enter your Startup Idea",
            placeholder="e.g., Eco-friendly tiffin delivery near tech parks."
        )
        validate_btn = gr.Button("Validate Idea")
        gr.HTML("<h3>Or choose a sample idea below:</h3>")
        dropdown = gr.Dropdown(choices=sample_ideas, label="Pick a Sample Idea", interactive=True)
        outputs = [gr.Textbox(label=label, lines=2) for label in [
            "1. Domain", "2. Market Demand", "3. Target Audience",
            "4. Competitor Analysis", "5. Revenue Model",
            "6. Innovation Potential", "7. Build Possibility Score",
            "8. Key Features (simple)",
            "9. Strategic Suggestions"
        ]]

        # Download components for both PDF and PPT
        download_file_pdf = gr.File(label="Download Complete Analysis (PDF)")
        download_file_ppt = gr.File(label="Download Presentation (PPT)")

        validate_btn.click(
            fn=validate_idea,
            inputs=[idea_input],
            outputs=outputs + [download_file_pdf, download_file_ppt]
        )
        dropdown.change(
            fn=lambda x: x,
            inputs=[dropdown],
            outputs=[idea_input]
        ).then(
            fn=validate_idea,
            inputs=[idea_input],
            outputs=outputs + [download_file_pdf, download_file_ppt]
        )

demo.launch()