import json
from django.db import migrations, models


def backfill_seo_scores(apps, schema_editor):
    Insight = apps.get_model('insights', 'Insight')
    for post in Insight.objects.all():
        score = 0
        if post.title:                                                   score += 1
        tl = len(post.meta_title or '')
        if 30 <= tl <= 60:                                               score += 1
        dl = len(post.meta_description or '')
        if 50 <= dl <= 160:                                              score += 1
        if post.focus_keyword:                                           score += 1
        if post.canonical_url:                                           score += 1
        if post.tldr:                                                    score += 1
        try:
            if any(f.get('q') and f.get('a')
                   for f in (json.loads(post.faq_json) if post.faq_json else [])):
                score += 1
        except Exception:
            pass
        if post.thumbnail:                                               score += 1
        if post.og_image_url:                                            score += 1
        try:
            if any(s.get('url')
                   for s in (json.loads(post.sources_json) if post.sources_json else [])):
                score += 1
        except Exception:
            pass
        if post.author_title:                                            score += 1
        if post.author_bio:                                              score += 1
        if post.tags:                                                    score += 1
        post.seo_score = round(score / 13 * 100)
        post.save(update_fields=['seo_score'])


class Migration(migrations.Migration):

    dependencies = [
        ('insights', '0004_insight_is_visible'),
    ]

    operations = [
        migrations.AddField(
            model_name='insight',
            name='seo_score',
            field=models.PositiveSmallIntegerField(
                default=0,
                editable=False,
                help_text='Auto-computed 0-100. Posts below 60 are hidden from the public site.',
            ),
        ),
        migrations.RunPython(backfill_seo_scores, migrations.RunPython.noop),
    ]
