#!/usr/bin/env python3
"""
Check and populate missing AI News template properties
Designed to run on the production server
"""
import sys
import os
import json

# Add backend/src to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'backend', 'src'))

from app import app

with app.app_context():
    from db import get_db
    
    db = get_db()
    with db.cursor() as cursor:
        cursor.execute('''SELECT `key`, label, description, lead_text, extra_lines, image_generation_config 
                          FROM ai_news_template_defs ORDER BY `key`''')
        existing = {row['key']: row for row in cursor.fetchall()}
    
    # Template definitions
    TEMPLATE_DEFS = {
        'developer_news': {
            'label': 'Developer News Roundup',
            'description': 'Structured digest for broad developer news and industry updates.',
            'lead_text': 'Generate up to 3 original developer-focused news articles summarizing the most relevant updates.',
            'extra_lines': [
                'Each body_md must use Markdown headings with at least three concise paragraphs and bullet lists when helpful.',
                'Highlight why each update matters for engineers and their day-to-day work.',
                'Format every article with these Markdown sections in order: ## Summary (2-3 sentences), ## Key Developments (bullet list), ## Impact on Developers (two paragraphs), ## Additional Resources (bulleted links).',
                'Use bold text for product or technology names on first mention in each article.',
            ],
            'image_generation_config': {
                'enabled': True,
                'frequency': 'per_article',
                'style': 'tech-modern',
            }
        },
        'code_examples': {
            'label': 'Code Tutorial Spotlight',
            'description': 'Hands-on walkthroughs anchored by reusable code snippets.',
            'lead_text': 'Generate up to 3 tutorial-style updates that revolve around practical code examples or patterns developers can reuse.',
            'extra_lines': [
                'Ensure each body_md includes Markdown headings and at least one fenced code block annotated with the language (e.g., ```javascript).',
                'Explain the problem the code solves, why it matters right now, and how to adapt it.',
                'Structure each article with these Markdown sections in order: ## Problem, ## Why It Matters, ## Code Walkthrough (include the code fence), ## Implementation Notes, ## References.',
                'Keep explanations approachable for mid-level engineers while staying technically precise.',
            ],
            'image_generation_config': {
                'enabled': True,
                'frequency': 'hero_only',
                'style': 'code-focused',
            }
        },
        'anime_news': {
            'label': 'Anime News Flash',
            'description': 'Anime and manga developments framed for tech-savvy fans.',
            'lead_text': 'Generate up to 3 anime and manga news capsules covering studio announcements, release schedules, and fan community updates.',
            'extra_lines': [
                'Use Markdown headings with at least two short paragraphs and a bullet list highlighting key community reactions.',
                'Structure each article with these Markdown sections in order: ## Headline Scoop, ## Studio & Release Details, ## Why Fans Will Care, ## Community Buzz, ## Source Links.',
                'Blend TheCodeSaiyan voice with anime flair—enthusiastic, witty, and tech-savvy without slipping into meme-only language.',
                'Focus on studio announcements, release dates, platform availability, character announcements, and fan engagement.',
            ],
            'image_generation_config': {
                'enabled': True,
                'frequency': 'per_article',
                'style': 'anime-vibrant',
                'use_emojis': True,
            }
        },
        'product_launches': {
            'label': 'Product Launch Brief',
            'description': 'Coverage of launches and feature drops that matter to builders.',
            'lead_text': 'Generate up to 3 product launch briefings for tools or platforms that impact builders.',
            'extra_lines': [
                'Each body_md must include Markdown headings, one bulleted list of key capabilities, and at least two short paragraphs describing impact.',
                'Structure each article with these Markdown sections in order: ## Launch Overview, ## Key Capabilities (bullet list), ## Impact on Builders, ## Getting Started, ## Source Links.',
                'Call out pricing, availability, or access requirements when the information is publicly known.',
            ],
            'image_generation_config': {
                'enabled': True,
                'frequency': 'per_article',
                'style': 'product-showcase',
            }
        },
        'event_recap': {
            'label': 'Event Recap Breakdown',
            'description': 'Summaries of conferences or livestreams with actionable takeaways.',
            'lead_text': 'Generate up to 3 recap articles summarizing recent developer events, livestreams, or conferences.',
            'extra_lines': [
                'Each body_md must use Markdown headings, include a bullet list of standout moments, and offer at least two reflective paragraphs.',
                'Structure each article with these Markdown sections in order: ## Event Snapshot, ## Biggest Announcements, ## Takeaways for Developers, ## Speaker Shout-outs, ## Watch/Read More.',
                'Encourage readers to explore recordings or slides with actionable links.',
            ],
            'image_generation_config': {
                'enabled': True,
                'frequency': 'hero_only',
                'style': 'event-professional',
            }
        },
        'tv_show_recap': {
            'label': 'TV Show Recap',
            'description': 'Episode recaps and TV series news for streaming platforms and broadcast television.',
            'lead_text': 'Generate up to 3 TV show recap articles covering recent episodes, series news, and streaming platform updates.',
            'extra_lines': [
                'Each body_md must use Markdown headings with at least three engaging paragraphs and bullet lists for key plot points.',
                'Structure each article with these Markdown sections in order: ## Episode/Series Overview, ## Key Moments (bullet list), ## Character Developments, ## Tech & Production Notes, ## Where to Watch.',
                'Balance entertainment coverage with technical aspects like streaming tech, production tools, or visual effects when relevant.',
                'Include episode numbers, air dates, and platform availability clearly.',
            ],
            'image_generation_config': {
                'enabled': True,
                'frequency': 'per_article',
                'style': 'entertainment-vibrant',
            }
        },
        'movie_news': {
            'label': 'Movie News & Reviews',
            'description': 'Film industry news, movie releases, reviews, and box office updates.',
            'lead_text': 'Generate up to 3 movie news articles covering releases, reviews, box office updates, and film industry developments.',
            'extra_lines': [
                'Each body_md must use Markdown headings with at least three well-structured paragraphs and bullet lists for key details.',
                'Structure each article with these Markdown sections in order: ## Film Overview, ## Critical Reception, ## Box Office & Release Details, ## Behind the Scenes, ## Viewer Resources.',
                'Highlight any technical innovations in cinematography, visual effects, or production tools that developers might find interesting.',
                'Include release dates, platforms (theatrical/streaming), and where to find more information.',
            ],
            'image_generation_config': {
                'enabled': True,
                'frequency': 'per_article',
                'style': 'cinema-dramatic',
            }
        },
        'gaming_news': {
            'label': 'Gaming News Blast',
            'description': 'Gaming industry updates with energetic tone and community focus.',
            'lead_text': 'Generate up to 3 gaming news articles covering game releases, updates, esports, and gaming community highlights.',
            'extra_lines': [
                'Each article should include release dates, platform information, and gaming community reactions.',
                'Use Markdown sections: ## Game/Update Overview, ## Key Features, ## Community Reaction, ## Where to Play, ## Additional Links.',
                'Blend tech coverage with gaming culture—mention streaming platforms, cross-platform support, and esports news.',
                'Keep tone energetic and community-focused.',
            ],
            'image_generation_config': {
                'enabled': True,
                'frequency': 'per_article',
                'style': 'gaming',
                'use_emojis': True,
            }
        },
        'quick_tech_tips': {
            'label': 'Quick Tech Tips',
            'description': 'Bite-sized actionable tech tips and productivity hacks.',
            'lead_text': 'Generate up to 5 short, actionable tech tips and productivity hacks for developers.',
            'extra_lines': [
                'Each tip should be concise (2-3 sentences) and immediately actionable.',
                'Format: ## Tip Title, Brief explanation, Link to resource or tool.',
                'Include keyboard shortcuts, command-line tricks, IDE hacks, or tool configurations.',
                'Make each tip independently useful and quick to scan.',
            ],
            'image_generation_config': {
                'enabled': False,
                'frequency': 'none',
                'use_emojis': True,
            }
        },
        'weekly_roundup': {
            'label': 'Weekly Tech Roundup',
            'description': 'Comprehensive weekly digest of tech news and highlights.',
            'lead_text': 'Generate a comprehensive weekly roundup of the top 5-7 tech news items and highlights.',
            'extra_lines': [
                'Create a structured digest with category headers (AI, Web Dev, Security, etc.).',
                'Use Markdown sections: ## Week Overview, ## Top Stories (with descriptions), ## Key Highlights, ## Resources & Links.',
                'Each story should have 2-3 sentences explaining why it matters.',
                'End with a brief outlook for the coming week.',
            ],
            'image_generation_config': {
                'enabled': True,
                'frequency': 'hero_only',
                'style': 'modern',
            }
        },
        'social_media_update': {
            'label': 'Social Media Update',
            'description': 'Short, punchy tech updates optimized for social sharing.',
            'lead_text': 'Generate 3-5 short, punchy tech updates optimized for social media platforms.',
            'extra_lines': [
                'Keep each update to 1-2 sentences maximum.',
                'Include hashtags relevant to the topic.',
                'Focus on immediate impact and shareability.',
                'Perfect for Twitter, LinkedIn, or social feeds.',
            ],
            'image_generation_config': {
                'enabled': True,
                'frequency': 'hero_only',
                'style': 'social',
                'use_emojis': True,
            }
        },
        'video_tutorial_recap': {
            'label': 'Video Tutorial Recap',
            'description': 'Summaries of video tutorials and livestream content.',
            'lead_text': 'Generate up to 3 recaps summarizing popular video tutorials and livestream content.',
            'extra_lines': [
                'Include video duration, platform (YouTube, Twitch, etc.), and creator information.',
                'Format: ## Video/Livestream Title, ## Quick Summary, ## Key Takeaways, ## Watch/Access Link.',
                'Highlight tools, libraries, or techniques demonstrated in the video.',
                'Make it easy for readers to find and watch the original content.',
            ],
            'image_generation_config': {
                'enabled': True,
                'frequency': 'per_article',
                'style': 'video',
            }
        },
        'podcast_summary': {
            'label': 'Podcast Episode Summary',
            'description': 'Concise summaries of tech podcast episodes with key takeaways.',
            'lead_text': 'Generate up to 3 summaries of recent tech podcast episodes.',
            'extra_lines': [
                'Include podcast name, episode title, hosts, and episode number.',
                'Format: ## Episode Overview, ## Key Takeaways (bullet list), ## Guests & Highlights, ## Listen/Subscribe Link.',
                'Focus on actionable insights and memorable moments.',
                'Make summaries useful for both listeners and non-listeners.',
            ],
            'image_generation_config': {
                'enabled': True,
                'frequency': 'hero_only',
                'style': 'podcast',
            }
        },
        'code_review_digest': {
            'label': 'Code Review Digest',
            'description': 'Technical analysis of code changes, PRs, and best practices.',
            'lead_text': 'Generate up to 3 code review digests analyzing interesting PRs and coding patterns.',
            'extra_lines': [
                'Include repository name, language, and key code snippets.',
                'Format: ## PR Overview, ## Code Analysis, ## Best Practices Highlighted, ## Lessons Learned, ## Repository Link.',
                'Use code fences to highlight important changes.',
                'Focus on educational value and patterns that apply broadly.',
            ],
            'image_generation_config': {
                'enabled': False,
                'frequency': 'none',
            }
        },
        'case_study_spotlight': {
            'label': 'Case Study Spotlight',
            'description': 'In-depth case studies of successful tech implementations.',
            'lead_text': 'Generate up to 3 in-depth case studies of successful tech implementations and projects.',
            'extra_lines': [
                'Format: ## Project Overview, ## Challenge & Solution, ## Technologies Used, ## Results & Impact, ## Lessons Learned, ## Further Reading.',
                'Include metrics and quantifiable results when available.',
                'Focus on real-world implementation challenges and solutions.',
                'Highlight transferable lessons for readers.',
            ],
            'image_generation_config': {
                'enabled': True,
                'frequency': 'hero_only',
                'style': 'professional',
            }
        },
        'academic_research_brief': {
            'label': 'Academic Research Brief',
            'description': 'Summaries of academic papers and research in tech.',
            'lead_text': 'Generate up to 3 summaries of recent academic papers and research findings in technology.',
            'extra_lines': [
                'Include paper title, authors, institution, and publication venue.',
                'Format: ## Research Overview, ## Key Findings, ## Methodology, ## Implications for Industry, ## Full Paper Link.',
                'Translate academic language into practical insights.',
                'Focus on papers with real-world applications.',
            ],
            'image_generation_config': {
                'enabled': False,
                'frequency': 'none',
            }
        },
        'newsletter_format': {
            'label': 'Newsletter Edition',
            'description': 'Comprehensive newsletter-style compilation of tech updates.',
            'lead_text': 'Generate a full newsletter edition with curated tech news and insights.',
            'extra_lines': [
                'Structure: Opening Message, Top Stories (3-5 items), Featured Deep Dive, Community Highlights, Call-to-Action.',
                'Each section should flow naturally and feel editorially curated.',
                'Include a personal touch and TheCodeSaiyan perspective.',
                'Format for email delivery or web publishing.',
            ],
            'image_generation_config': {
                'enabled': True,
                'frequency': 'hero_only',
                'style': 'modern',
            }
        },
        'changelog_update': {
            'label': 'Changelog & Release Notes',
            'description': 'Software release notes and changelog summaries.',
            'lead_text': 'Generate up to 4 changelog and release notes summaries for software updates.',
            'extra_lines': [
                'Format: ## Release Overview, ## New Features, ## Bug Fixes & Improvements, ## Breaking Changes (if any), ## Upgrade Path.',
                'Use clear Markdown formatting with code fences for CLI commands.',
                'Include version numbers and release dates.',
                'Highlight impact on existing users.',
            ],
            'image_generation_config': {
                'enabled': False,
                'frequency': 'none',
            }
        },
        'deep_dive_tech': {
            'label': 'Deep Dive Analysis',
            'description': 'Comprehensive technical deep dives and long-form analysis.',
            'lead_text': 'Generate 1 comprehensive technical deep dive or long-form analysis article.',
            'extra_lines': [
                'Format: ## Introduction, ## Background, ## Core Concepts, ## Implementation Details (with code examples), ## Trade-offs & Alternatives, ## Future Developments, ## Conclusion.',
                'Target length: 3000+ words of substantive content.',
                'Include code samples, diagrams (describe in Markdown), and links to resources.',
                'Provide expert-level insights and analysis.',
            ],
            'image_generation_config': {
                'enabled': True,
                'frequency': 'hero_only',
                'style': 'tech-analytical',
            }
        },
    }
    
    print("\n" + "="*80)
    print("AI NEWS TEMPLATE POPULATION REPORT")
    print("="*80)
    
    updates_needed = []
    
    for key, template_def in TEMPLATE_DEFS.items():
        existing_row = existing.get(key)
        
        missing_fields = []
        if not existing_row:
            missing_fields = ['all']
            print(f"\n⚠️  NEW TEMPLATE: {key}")
        else:
            if not existing_row.get('label'):
                missing_fields.append('label')
            if not existing_row.get('description'):
                missing_fields.append('description')
            if not existing_row.get('lead_text'):
                missing_fields.append('lead_text')
            if not existing_row.get('extra_lines'):
                missing_fields.append('extra_lines')
            if not existing_row.get('image_generation_config'):
                missing_fields.append('image_generation_config')
        
        if missing_fields:
            print(f"\n❌ MISSING: {key}")
            print(f"   Fields: {', '.join(missing_fields)}")
            updates_needed.append((key, template_def))
        else:
            print(f"\n✅ COMPLETE: {key}")
    
    if updates_needed:
        print(f"\n\n{'='*80}")
        print(f"POPULATING {len(updates_needed)} TEMPLATE(S)")
        print("="*80)
        
        with db.cursor() as cursor:
            for key, template_def in updates_needed:
                extra_lines_json = json.dumps(template_def['extra_lines'])
                image_config_json = json.dumps(template_def['image_generation_config'])
                
                sql = '''INSERT INTO ai_news_template_defs 
                         (`key`, label, description, lead_text, extra_lines, image_generation_config, version)
                         VALUES (%s, %s, %s, %s, %s, %s, 1)
                         ON DUPLICATE KEY UPDATE
                         label = VALUES(label),
                         description = VALUES(description),
                         lead_text = VALUES(lead_text),
                         extra_lines = VALUES(extra_lines),
                         image_generation_config = VALUES(image_generation_config)'''
                
                try:
                    cursor.execute(sql, (
                        key,
                        template_def['label'],
                        template_def['description'],
                        template_def['lead_text'],
                        extra_lines_json,
                        image_config_json,
                    ))
                    print(f"✅ Updated/Created: {key}")
                except Exception as e:
                    print(f"❌ Failed to update {key}: {e}")
            
            db.commit()
        print(f"\n✅ All templates populated successfully!")
    else:
        print(f"\n\n✅ All templates are complete!")
