File size: 30,161 Bytes
e7251ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86a7494
 
e7251ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from utils import *
from youtube_api_test import *
import traceback
import datetime
import json
import plotly.graph_objects as go
from plotly.subplots import make_subplots


def analyze_detailed_comments_sentiment(videos_data, content_type="videos", max_videos=5):
    if not videos_data:
        return {}
    
    batch_content = f"Analyze {content_type} comments in detail with reasoning:\n\n"
    
    for i, (video_id, title, likes, comments) in enumerate(videos_data[:max_videos]):
        comment_data = []
        for j, (comment, like_count) in enumerate(zip(comments[:30], likes[:30])):
            comment_data.append(f"- \"{comment}\" ({like_count} likes)")
        
        comments_text = '\n'.join(comment_data)[:2500]
        
        batch_content += f"""
VIDEO {i}: "{title[:120]}"
COMMENTS WITH LIKES:
{comments_text}
---
"""
    
    batch_prompt = f"""
{batch_content}
**Note: Advanced sentiment analysis required - consider sarcasm, slang, emojis, and context**
For each video, analyze the comments and extract multiple top comments by sentiment. Provide detailed analysis in this EXACT JSON format:

{{
    "video_0": {{
        "sentiment": "positive",
        "score": 0.7,
        "positive_ratio": 65,
        "negative_ratio": 15,
        "key_themes": ["collaboration", "creativity"],
        "engagement_quality": "high",
        "best_positives": [
            {{"comment": "Amazing collaboration with small creators!", "likes": 150}},
            {{"comment": "Love this authentic content!", "likes": 89}},
            {{"comment": "Best video this year!", "likes": 67}}
        ],
        "best_negatives": [
            {{"comment": "Audio quality could be better", "likes": 45}},
            {{"comment": "Too long, should be shorter", "likes": 23}},
            {{"comment": "Boring content lately", "likes": 12}}
        ],
        "best_neutrals": [
            {{"comment": "Thanks for the content", "likes": 34}},
            {{"comment": "First!", "likes": 89}},
            {{"comment": "When is the next upload?", "likes": 56}}
        ],
        "positive_reasons": [
            "Viewers appreciate authentic collaborations and humble attitude",
            "High production quality and engaging storytelling",
            "Strong community connection and interaction"
        ],
        "negative_reasons": [
            "Technical issues mentioned by some viewers",
            "Content length concerns from audience",
            "Some want more variety in topics"
        ],
        "trend_analysis": "Strong positive trend due to community focus and authentic content"
    }},
    "video_1": {{
        "sentiment": "neutral",
        "score": 0.5,
        "positive_ratio": 45,
        "negative_ratio": 25,
        "key_themes": ["gaming", "entertainment"],
        "engagement_quality": "medium",
        "best_positives": [
            {{"comment": "Good gameplay as always", "likes": 78}},
            {{"comment": "Nice skills bro", "likes": 45}}
        ],
        "best_negatives": [
            {{"comment": "Not your best work", "likes": 34}},
            {{"comment": "Too repetitive", "likes": 23}}
        ],
        "best_neutrals": [
            {{"comment": "Part 2 when?", "likes": 67}},
            {{"comment": "Early squad", "likes": 89}}
        ],
        "positive_reasons": [
            "Consistent quality appreciated by fans",
            "Good technical skills recognized"
        ],
        "negative_reasons": [
            "Some viewers want more innovation",
            "Content feels repetitive to some"
        ],
        "trend_analysis": "Steady engagement but needs fresh elements"
    }}
}}

IMPORTANT REQUIREMENTS:
0. If comments are not in English. Translate it in English.
1. Extract 2-3 best comments for each sentiment category (positive, negative, neutral)
2. Include actual comment text and like counts from the data provided. 
3. Ensure like counts match the data given
4. Provide 2-3 specific reasons for positive and negative sentiment patterns
5. Make sure positive_ratio + negative_ratio + neutral_ratio roughly equals 100
6. Return ONLY valid JSON without markdown formatting
7. Use actual quotes from the comments provided. Do not change the raw comments if it includes likes.
"""
    
    try:
        print(f"🧠 Sending {len(videos_data)} videos to AI for multi-comment sentiment analysis...")
        response = client.chat.completions.create(
            model="gpt-4o-mini", 
            messages=[{"role": "user", "content": batch_prompt}], 
            max_tokens=3000,
            temperature=0.5
        )
        
        response_text = response.choices[0].message.content.strip()
        print(f"πŸ“₯ Received AI response: {len(response_text)} characters")
        
        if "```json" in response_text:
            response_text = response_text.split("```json")[1].split("```")[0].strip()
        elif "```" in response_text:
            response_text = response_text.split("```")[1].split("```")[0].strip()
        
        response_text = response_text.strip()
        if not response_text.startswith('{'):
            start_idx = response_text.find('{')
            end_idx = response_text.rfind('}') + 1
            if start_idx != -1 and end_idx != 0:
                response_text = response_text[start_idx:end_idx]
        
        print(f"πŸ”§ Cleaned response for JSON parsing...")
        batch_results = json.loads(response_text)
        print(f"βœ… Successfully parsed AI analysis for {len(batch_results)} {content_type}")
        return batch_results
        
    except json.JSONDecodeError as e:
        print(f"❌ JSON parsing error: {e}")
        print(f"❌ Raw response: {response_text[:500]}...")
        
        fallback_results = {}
        for i in range(min(len(videos_data), max_videos)):
            video_id, title, likes, comments = videos_data[i]
            
            sample_positives = []
            sample_negatives = []
            sample_neutrals = []
            
            for j, (comment, like_count) in enumerate(zip(comments[:10], likes[:10])):
                if j < 3:
                    sample_positives.append({"comment": comment[:100], "likes": like_count})
                elif j < 6:
                    sample_negatives.append({"comment": comment[:100], "likes": like_count})
                else:
                    sample_neutrals.append({"comment": comment[:100], "likes": like_count})
            
            fallback_results[f"video_{i}"] = {
                "sentiment": "neutral",
                "score": 0.5 + (i * 0.1),
                "positive_ratio": 50 + (i * 5),
                "negative_ratio": 20 + (i * 2),
                "key_themes": ["content", "entertainment", "youtube"],
                "engagement_quality": "medium",
                "best_positives": sample_positives or [{"comment": "Great video!", "likes": 50}],
                "best_negatives": sample_negatives or [{"comment": "Could improve", "likes": 20}],
                "best_neutrals": sample_neutrals or [{"comment": "Thanks for content", "likes": 30}],
                "positive_reasons": [
                    "General audience appreciation",
                    "Consistent content quality"
                ],
                "negative_reasons": [
                    "Minor technical improvements needed",
                    "Some content preferences vary"
                ],
                "trend_analysis": "Steady engagement with growth potential"
            }
        print(f"πŸ”„ Using enhanced fallback data for {len(fallback_results)} videos")
        return fallback_results
        
    except Exception as e:
        print(f"❌ Sentiment analysis error: {e}")
        print(f"❌ Full error: {traceback.format_exc()}")
        
        basic_fallback = {}
        for i in range(min(len(videos_data), max_videos)):
            basic_fallback[f"video_{i}"] = {
                "sentiment": "neutral", "score": 0.4, "positive_ratio": 40, 
                "negative_ratio": 30, "key_themes": ["general"], "engagement_quality": "medium",
                "best_positives": [{"comment": "Good content", "likes": 25}],
                "best_negatives": [{"comment": "Could improve", "likes": 15}],
                "best_neutrals": [{"comment": "Thanks", "likes": 20}],
                "positive_reasons": ["Basic appreciation"],
                "negative_reasons": ["General feedback"],
                "trend_analysis": "Stable engagement"
            }
        print(f"πŸ”„ Using basic fallback for {len(basic_fallback)} videos")
        return basic_fallback

def create_content_dashboard(content_df, content_type="Videos"):
    """Create specialized dashboard for videos or shorts"""
    if content_df.empty:
        fig = go.Figure()
        fig.add_annotation(text=f"No {content_type.lower()} found for analysis", 
                         xref="paper", yref="paper", x=0.5, y=0.5, showarrow=False)
        return fig
    
    fig = make_subplots(
        rows=2, cols=2,
        subplot_titles=(
            f'πŸ“ˆ {content_type} Sentiment Trend & Performance',
            f'πŸ“Š {content_type} Sentiment Distribution', 
            f'πŸ’‘ Engagement Quality Breakdown',
            f'πŸ”₯ Performance vs Sentiment Correlation'
        ),
        specs=[
            [{"secondary_y": True}, {"type": "pie"}],
            [{"type": "bar"}, {"type": "scatter"}]
        ],
        vertical_spacing=0.15,
        horizontal_spacing=0.12
    )
    
    content_labels = [f"{content_type[:-1]} {i+1}" for i in range(len(content_df))]
    colors = ['#2E86DE' if content_type == 'Videos' else '#FF6B35'] * len(content_df)
    
    fig.add_trace(
        go.Scatter(
            x=content_labels,
            y=content_df['sentiment_score'],
            mode='lines+markers',
            marker=dict(size=12, color=colors[0], line=dict(width=2, color='white')),
            line=dict(width=4, color=colors[0]),
            name=f'{content_type} Sentiment',
            hovertemplate='<b>%{x}</b><br>Sentiment: %{y:.2f}<extra></extra>'
        ),
        row=1, col=1
    )
    
    # Add views as bars
    fig.add_trace(
        go.Bar(
            x=content_labels,
            y=content_df['views']/1000,
            name='Views (K)',
            opacity=0.4,
            marker_color=colors[0],
            hovertemplate='<b>%{x}</b><br>Views: %{y:.0f}K<extra></extra>'
        ),
        row=1, col=1, secondary_y=True
    )
    
    # Sentiment distribution pie
    avg_positive = content_df['positive_ratio'].mean()
    avg_negative = content_df['negative_ratio'].mean()
    avg_neutral = 100 - avg_positive - avg_negative
    
    fig.add_trace(
        go.Pie(
            labels=['😊 Positive', '😐 Neutral', '😠 Negative'],
            values=[avg_positive, avg_neutral, avg_negative],
            marker_colors=['#2ECC71', '#95A5A6', '#E74C3C'],
            hole=0.4,
            hovertemplate='<b>%{label}</b><br>%{value:.1f}%<extra></extra>',
            textinfo='label+percent',
            textfont=dict(size=12, color='white')
        ),
        row=1, col=2
    )
    
    # Engagement quality breakdown
    engagement_counts = content_df['engagement_quality'].value_counts()
    quality_colors = {'high': '#27AE60', 'medium': '#F39C12', 'low': '#E74C3C'}
    
    fig.add_trace(
        go.Bar(
            x=engagement_counts.index,
            y=engagement_counts.values,
            marker_color=[quality_colors.get(q, '#95A5A6') for q in engagement_counts.index],
            hovertemplate='<b>%{x} Quality</b><br>Count: %{y}<extra></extra>',
            text=engagement_counts.values,
            textposition='auto',
            textfont=dict(size=14, color='white')
        ),
        row=2, col=1
    )
    
    # Performance vs Sentiment scatter
    fig.add_trace(
        go.Scatter(
            x=content_df['sentiment_score'],
            y=content_df['views'],
            mode='markers',
            marker=dict(
                size=content_df['positive_ratio']/3,
                color=content_df['sentiment_score'],
                colorscale='RdYlGn',
                showscale=True,
                colorbar=dict(title="Sentiment Score"),
                line=dict(width=2, color='white')
            ),
            text=[f"{content_type[:-1]} {i+1}" for i in range(len(content_df))],
            hovertemplate='<b>%{text}</b><br>Sentiment: %{x:.2f}<br>Views: %{y:,}<extra></extra>'
        ),
        row=2, col=2
    )
    
    fig.update_layout(
        height=800,
        showlegend=False,
        title_text=f"🎯 {content_type} Analytics Dashboard - AI-Powered Insights",
        title_font=dict(size=20, color='#2C3E50'),
        title_x=0.5,
        plot_bgcolor='white',
        paper_bgcolor='white'
    )
    
    # Update axes
    fig.update_yaxes(title_text="Sentiment Score", row=1, col=1)
    fig.update_yaxes(title_text="Views (K)", row=1, col=1, secondary_y=True)
    fig.update_xaxes(title_text="Content Index", row=1, col=1, tickangle=45)
    fig.update_xaxes(title_text="Sentiment Score", row=2, col=2)
    fig.update_yaxes(title_text="Views", row=2, col=2)
    
    return fig

def analyze_content_batch(channel_input, content_type="videos", max_videos=5):
    """Analyze either videos or shorts with detailed insights"""
    try:
        print(f"πŸš€ Starting {content_type} analysis for: {channel_input} (Max: {max_videos})")
        channel_id = get_channel_id_by_name(channel_input)
        if not channel_id:
            print(f"❌ Channel '{channel_input}' not found!")
            return None

        if content_type == "videos":
            content_df = get_channel_videos(channel_id, limit=max_videos)
            emoji = "πŸ“Ή"
        else:
            content_df = get_channel_shorts(channel_id, limit=max_videos)
            emoji = "🎬"
        
        if content_df.empty:
            return f"## {emoji} No {content_type} found\n\nThis channel doesn't have any {content_type} to analyze.", go.Figure()
        
        # Initialize columns
        content_df['sentiment_score'] = 0.0
        content_df['positive_ratio'] = 0.0
        content_df['negative_ratio'] = 0.0
        content_df['key_themes'] = None
        content_df['engagement_quality'] = 'medium'
        content_df['best_positive'] = ''
        content_df['best_negative'] = ''
        content_df['best_neutral'] = ''
        content_df['positive_reason'] = ''
        content_df['negative_reason'] = ''
        content_df['trend_analysis'] = ''
        content_df['best_positives'] = None 
        content_df['best_negatives'] = None 
        content_df['best_neutrals'] = None  
        content_df['positive_reasons'] = None 
        content_df['negative_reasons'] = None

        print(f"πŸ“Š Collecting {content_type} comments...")
        batch_data = []
        for i, row in content_df.iterrows():
            comments_df = get_youtube_comments(row['video_id'], limit=17, order='relevance')
            if not comments_df.empty:
                batch_data.append((row['video_id'], row['title'], comments_df['likes'].tolist(), comments_df['comment'].tolist()))
        
        if batch_data:
            print(f"🧠 AI analyzing {len(batch_data)} {content_type}...")
            results = analyze_detailed_comments_sentiment(batch_data, content_type, max_videos)
            
        for i, (video_id, title, likes, comments) in enumerate(batch_data):
            result_key = f"video_{i}"
            if result_key in results:
                result = results[result_key]
                try:
                    idx = content_df[content_df['video_id'] == video_id].index[0]
                    
                    # Apply basic metrics
                    content_df.at[idx, 'sentiment_score'] = result.get('score', 0)
                    content_df.at[idx, 'positive_ratio'] = result.get('positive_ratio', 0)
                    content_df.at[idx, 'negative_ratio'] = result.get('negative_ratio', 0)
                    content_df.at[idx, 'key_themes'] = result.get('key_themes', [])
                    content_df.at[idx, 'engagement_quality'] = result.get('engagement_quality', 'medium')
                    content_df.at[idx, 'trend_analysis'] = result.get('trend_analysis', '')
                    
                    # Apply multiple comments and reasons
                    content_df.at[idx, 'best_positives'] = result.get('best_positives', [])
                    content_df.at[idx, 'best_negatives'] = result.get('best_negatives', [])
                    content_df.at[idx, 'best_neutrals'] = result.get('best_neutrals', [])
                    content_df.at[idx, 'positive_reasons'] = result.get('positive_reasons', [])
                    content_df.at[idx, 'negative_reasons'] = result.get('negative_reasons', [])
                    
                    # Keep single comment fields for backward compatibility
                    best_pos = result.get('best_positives', [])
                    best_neg = result.get('best_negatives', [])
                    best_neu = result.get('best_neutrals', [])
                    
                    content_df.at[idx, 'best_positive'] = best_pos[0]['comment'] if best_pos else ''
                    content_df.at[idx, 'best_negative'] = best_neg[0]['comment'] if best_neg else ''
                    content_df.at[idx, 'best_neutral'] = best_neu[0]['comment'] if best_neu else ''
                    
                    pos_reasons = result.get('positive_reasons', [])
                    neg_reasons = result.get('negative_reasons', [])
                    
                    content_df.at[idx, 'positive_reason'] = pos_reasons[0] if pos_reasons else ''
                    content_df.at[idx, 'negative_reason'] = neg_reasons[0] if neg_reasons else ''
                    
                    print(f"βœ… Applied multi-comment analysis for: {title[:50]}...")
                    
                except Exception as e:
                    print(f"❌ Error applying results for {title[:50]}: {str(e)}")
        
        # Generate insights
        insights = generate_detailed_insights(content_df, content_type.capitalize())
        
        # Create dashboard
        dashboard = create_content_dashboard(content_df, content_type.capitalize())
        
        print(f"βœ… {content_type.capitalize()} analysis completed!")
        return insights, dashboard
        
    except Exception as e:
        print(f"❌ Error analyzing {content_type}: {str(e)}")
        error_msg = f"## ❌ {content_type.capitalize()} Analysis Error\n\n**Error:** {str(e)}"
        empty_fig = go.Figure()
        return error_msg, empty_fig


def generate_detailed_insights(content_df, content_type):
   """Generate AI-powered detailed insights with LLM analysis"""
   if content_df.empty:
       return f"## No {content_type.lower()} found for analysis"
   
   analysis_data = {
       "content_type": content_type,
       "total_content": len(content_df),
       "performance_metrics": {
           "avg_views": content_df['views'].mean(),
           "avg_sentiment": content_df['sentiment_score'].mean(),
           "avg_positive": content_df['positive_ratio'].mean(),
           "avg_negative": content_df['negative_ratio'].mean(),
           "total_views": content_df['views'].sum()
       },
       "content_breakdown": []
   }
   
   for i, row in content_df.iterrows():
       content_analysis = {
           "index": i + 1,
           "title": row['title'][:80],
           "views": row['views'],
           "sentiment_score": row['sentiment_score'],
           "positive_ratio": row.get('positive_ratio', 0),
           "negative_ratio": row.get('negative_ratio', 0),
           "engagement_quality": row.get('engagement_quality', 'medium'),
           "key_themes": row.get('key_themes', []),
           "best_positives": row.get('best_positives', []),
           "best_negatives": row.get('best_negatives', []),
           "positive_reasons": row.get('positive_reasons', []),
           "negative_reasons": row.get('negative_reasons', []),
           "trend_analysis": row.get('trend_analysis', '')
       }
       analysis_data["content_breakdown"].append(content_analysis)
   
   # Create LLM analysis prompt
   llm_prompt = f"""
Analyze this YouTube {content_type.lower()} performance data and generate a comprehensive intelligence report.

PERFORMANCE DATA:
- Total {content_type}: {analysis_data['total_content']}
- Average Views: {analysis_data['performance_metrics']['avg_views']:,.0f}
- Average Sentiment: {analysis_data['performance_metrics']['avg_sentiment']:.2f}/1.0
- Positive Ratio: {analysis_data['performance_metrics']['avg_positive']:.1f}%
- Negative Ratio: {analysis_data['performance_metrics']['avg_negative']:.1f}%

INDIVIDUAL CONTENT ANALYSIS:
{chr(10).join([f"{item['index']}. '{item['title']}' - {item['views']:,} views, {item['sentiment_score']:.2f} sentiment, {item['positive_ratio']:.0f}% positive, Quality: {item['engagement_quality']}, Themes: {item['key_themes'][:3]}" for item in analysis_data['content_breakdown']])}

Generate a professional analysis report in the following structure:

# πŸ† {content_type} Performance Intelligence Report

## πŸ“Š Executive Summary
[2-3 sentences about overall performance and key findings]

## 🎯 Performance Breakdown

### πŸ“ˆ Champion Content Analysis
[Identify top 2-3 performing videos with specific reasons for success]

### ⚠️ Optimization Opportunities  
[Identify bottom 2-3 performing videos with specific improvement recommendations]

## πŸ’‘ Strategic Insights

### πŸ”₯ Winning Formula
[3-4 key success patterns identified from top performers]

### 🎬 Content DNA Analysis
[Analysis of themes, engagement patterns, and audience preferences]

### πŸ“Š Audience Sentiment Intelligence
[Deep dive into comment sentiment patterns and audience behavior]

## πŸš€ Action Plan Recommendations

### Immediate Actions
[1-2 specific, actionable recommendations]

## πŸ† Competitive Advantage
[How this channel can differentiate and excel in their niche]

---

Requirements:
- Use emojis strategically for visual impact
- Include specific data points and percentages
- Make recommendations actionable and specific
- Write in professional but engaging tone
- Focus on growth and optimization strategies
- Keep analysis data-driven and insightful
"""

   try:
       # Generate LLM insights
       print("🧠 Generating AI-powered strategic insights...")
       response = client.chat.completions.create(
           model="gpt-4o-mini",
           messages=[{"role": "user", "content": llm_prompt}],
           max_tokens=3000,
           temperature=0.3
       )
       
       llm_insights = response.choices[0].message.content.strip()
       
       # Add individual content performance cards
       detailed_breakdown = """

---

<details>
<summary style="font-size: 1.5em; font-weight: bold; cursor: pointer; margin: 16px 0 8px 0; color: inherit;">
Individual Content Performance Matrix<br> (Click to Expand!)
</summary>

## πŸ“‹ Individual Content Performance Matrix

"""
       
       for item in analysis_data["content_breakdown"]:
           # Performance rating logic
           performance_score = (
               (item['sentiment_score'] * 40) + 
               (min(item['views'] / analysis_data['performance_metrics']['avg_views'], 2) * 30) +
               (item['positive_ratio'] * 0.3)
           )
           
           if performance_score >= 80:
               rating = "πŸ† CHAMPION"
               status_color = "πŸ’š"
           elif performance_score >= 60:
               rating = "πŸš€ STRONG"
               status_color = "πŸ’›"
           elif performance_score >= 40:
               rating = "πŸ“Š STEADY"
               status_color = "🟠"
           else:
               rating = "⚠️ NEEDS WORK"
               status_color = "πŸ’”"
           
           detailed_breakdown += f"""
### {rating}: "{item['title']}"

| Metric | Value | Performance |
|--------|--------|-------------|
| πŸ‘€ **Views** | {item['views']:,} | {status_color} {'Above Average' if item['views'] > analysis_data['performance_metrics']['avg_views'] else 'Below Average'} |
| 🎯 **Sentiment Score** | {item['sentiment_score']:.2f}/1.0 | {'πŸ”₯ Excellent' if item['sentiment_score'] > 0.8 else 'πŸ‘ Good' if item['sentiment_score'] > 0.6 else '⚠️ Needs Work'} |
| πŸ‘ **Positive Feedback** | {item['positive_ratio']:.0f}% | {'πŸ† Outstanding' if item['positive_ratio'] > 80 else 'πŸ“ˆ Strong' if item['positive_ratio'] > 60 else 'πŸ”§ Improve'} |
| πŸŽͺ **Engagement Quality** | {item['engagement_quality'].title()} | {'πŸ”₯ High Impact' if item['engagement_quality'] == 'high' else 'πŸ“Š Steady Growth' if item['engagement_quality'] == 'medium' else 'πŸ’‘ Potential'} |

**🎨 Content Themes**: {', '.join(item['key_themes'][:3]) if item['key_themes'] else 'General Content'}

"""
           # Positive feedback section
           if item.get('best_positives') or item.get('positive_reasons'):
               detailed_breakdown += "| **😊 Top Comments** | **😊 Positive Reasons** |\n"
               detailed_breakdown += "|---------------------|------------------------|\n"
               
               max_len = max(len(item.get('best_positives', [])), len(item.get('positive_reasons', [])))
               for i in range(max_len):
                   comment = item.get('best_positives', [])[i]['comment'][:100] + "..." if i < len(item.get('best_positives', [])) else ""
                   reason = item.get('positive_reasons', [])[i][:100] + "..." if i < len(item.get('positive_reasons', [])) else ""
                   detailed_breakdown += f"| {comment} | {reason} |\n"
               detailed_breakdown += "\n"
           
           # Negative feedback section
           if item.get('best_negatives') or item.get('negative_reasons'):
               detailed_breakdown += "| **πŸ” Critical Feedback** | **πŸ” Negative Reasons** |\n"
               detailed_breakdown += "|--------------------------|------------------------|\n"
               
               max_len = max(len(item.get('best_negatives', [])), len(item.get('negative_reasons', [])))
               for i in range(max_len):
                   comment = item.get('best_negatives', [])[i]['comment'][:100] + "..." if i < len(item.get('best_negatives', [])) else ""
                   reason = item.get('negative_reasons', [])[i][:100] + "..." if i < len(item.get('negative_reasons', [])) else ""
                   detailed_breakdown += f"| {comment} | {reason} |\n"
               detailed_breakdown += "\n"
           
           detailed_breakdown += "---\n"     
             
       detailed_breakdown += "\n</details>\n"
       
       # Combine LLM insights with detailed breakdown
       final_report = llm_insights + detailed_breakdown
       
       # Add footer with timestamp and hackathon branding
       final_report += f"""

---
*πŸ€– AI-Powered Strategic Intelligence | ⏰ {datetime.datetime.now().strftime('%Y-%m-%d %H:%M UTC')} | πŸ† Next-Gen Analytics*
"""
       
       print("βœ… Strategic intelligence report generated successfully!")
       return final_report
       
   except Exception as e:
       print(f"❌ LLM Analysis Error: {str(e)}")
       
       # Fallback to enhanced static analysis
       best_video = content_df.loc[content_df['sentiment_score'].idxmax()]
       worst_video = content_df.loc[content_df['sentiment_score'].idxmin()]
       
       fallback_report = f"""
# πŸ† {content_type} Performance Intelligence Report

## πŸ“Š Executive Dashboard

| 🎯 Key Metric | πŸ“ˆ Performance | 🎭 Status |
|---------------|----------------|-----------|
| **Portfolio Size** | {len(content_df)} {content_type.lower()} | {'πŸ”₯ Focused Strategy' if len(content_df) <= 10 else 'πŸ“Š Active Portfolio'} |
| **Average Performance** | {content_df['views'].mean():,.0f} views | {'πŸš€ Viral Territory' if content_df['views'].mean() > 1000000 else 'πŸ“ˆ Strong Growth' if content_df['views'].mean() > 100000 else 'πŸ‘ Building Momentum'} |
| **Audience Sentiment** | {content_df['sentiment_score'].mean():.2f}/1.0 | {'πŸ’š Exceptional' if content_df['sentiment_score'].mean() > 0.8 else 'πŸ‘ Positive' if content_df['sentiment_score'].mean() > 0.6 else '⚠️ Optimization Needed'} |
| **Success Rate** | {content_df['positive_ratio'].mean():.0f}% positive | {'πŸ† Championship Level' if content_df['positive_ratio'].mean() > 80 else 'πŸ“Š Competitive' if content_df['positive_ratio'].mean() > 60 else 'πŸ”§ Growth Opportunity'} |

## 🎯 Performance Analysis

### πŸ† TOP PERFORMER: "{best_video['title'][:60]}..."
- **πŸ“Š Metrics**: {best_video['views']:,} views | {best_video['sentiment_score']:.2f} sentiment | {best_video.get('positive_ratio', 0):.0f}% positive
- **βœ… Success DNA**: {best_video.get('positive_reason', 'Strong audience resonance and engaging content delivery')}

### ⚠️ OPTIMIZATION TARGET: "{worst_video['title'][:60]}..."
- **πŸ“Š Metrics**: {worst_video['views']:,} views | {worst_video['sentiment_score']:.2f} sentiment | {worst_video.get('positive_ratio', 0):.0f}% positive
- **πŸ”§ Growth Areas**: {worst_video.get('negative_reason', 'Content optimization and audience alignment needed')}

## πŸš€ Strategic Action Plan

### Immediate Wins (Next 30 Days)
1. **🎬 Replicate Success Formula**: Scale elements from "{best_video['title'][:30]}..." format
2. **πŸ”§ Optimize Underperformers**: Address feedback patterns from bottom performers
3. **πŸ“ˆ Engagement Boost**: Focus on {content_df['engagement_quality'].value_counts().index[0]} quality content

### Strategic Growth (Next 90 Days)
1. **🎯 Content Optimization**: Leverage top-performing themes and formats
2. **πŸ‘₯ Audience Development**: Build on positive sentiment patterns
3. **πŸ“Š Performance Scaling**: Systematic improvement of bottom 20% content

---
*πŸ€– Enhanced Analytics Engine | πŸ† MCP Server Hackathon | ⏰ {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')} | πŸš€ Next-Gen Intelligence*
"""
       return fallback_report