"""
Management command to remove broken placeholder image tags from blog article content.

Removes any <img> tags whose src points to example.com (e.g. placeholder URLs
that cause "broken external image" SEO errors).

Usage:
    python manage.py remove_blog_placeholder_images --url "https://example.com/blog/2026/1/22/..."
    python manage.py remove_blog_placeholder_images --all  # Process all articles with example.com images
    python manage.py remove_blog_placeholder_images --all --dry-run
"""
import re

from django.core.management.base import BaseCommand
from lotus.models import Article

from django_blog_plus.conf import django_blog_plus_settings
from django_blog_plus.webhook import get_article_by_url


# Match <img ... src="...example.com..." ...> (allowing for different attribute order)
EXAMPLE_COM_IMG_PATTERN = re.compile(
    r'<img\s[^>]*src\s*=\s*["\'][^"\']*example\.com[^"\']*["\'][^>]*>',
    re.IGNORECASE | re.DOTALL
)


def strip_example_com_images(html_content):
    """Remove img tags that reference example.com from HTML content."""
    if not html_content:
        return html_content
    return EXAMPLE_COM_IMG_PATTERN.sub('', html_content)


class Command(BaseCommand):
    help = 'Remove broken example.com placeholder images from blog article content'

    def add_arguments(self, parser):
        parser.add_argument(
            '--url',
            type=str,
            help='Full URL of a single article to fix (e.g. https://example.com/blog/2026/1/22/slug/)',
        )
        parser.add_argument(
            '--all',
            action='store_true',
            help='Process all articles that contain example.com image URLs',
        )
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Show what would be changed without saving',
        )

    def handle(self, *args, **options):
        url = options.get('url')
        process_all = options.get('all')
        dry_run = options.get('dry_run')

        if not url and not process_all:
            self.stderr.write(self.style.ERROR('Provide either --url or --all'))
            return

        language = django_blog_plus_settings.get_language_code()

        if url:
            article = get_article_by_url(url, language)
            if not article:
                self.stderr.write(self.style.ERROR(f'Article not found for URL: {url}'))
                return
            articles = [article]
        else:
            all_articles = list(Article.objects.filter(language=language))
            articles = [a for a in all_articles if a.content and 'example.com' in a.content]
            if not articles:
                self.stdout.write(self.style.SUCCESS('No articles contain example.com image URLs.'))
                return
            self.stdout.write(f'Found {len(articles)} article(s) with example.com in content.')

        fixed = 0
        for article in articles:
            original = article.content
            new_content = strip_example_com_images(original)
            if new_content == original:
                self.stdout.write(f'  [{article.id}] No change: {article.title[:50]}...')
                continue
            if dry_run:
                self.stdout.write(self.style.WARNING(f'  [DRY-RUN] Would update article {article.id}: {article.title[:50]}...'))
                fixed += 1
                continue
            article.content = new_content
            article.save(update_fields=['content'])
            self.stdout.write(self.style.SUCCESS(f'  Updated article {article.id}: {article.title[:50]}...'))
            fixed += 1

        if dry_run and fixed:
            self.stdout.write(self.style.WARNING(
                f'Dry run: would have updated {fixed} article(s). '
                'Run without --dry-run to apply.'
            ))
        elif fixed:
            self.stdout.write(self.style.SUCCESS(f'Updated {fixed} article(s).'))
