"""回滚误用 PDF 候选矫正的标题。"""
from django.core.management.base import BaseCommand
from django.utils import timezone

from apps.resm.models import Paper
from apps.resm.title_utils import assess_title


class Command(BaseCommand):
    help = "将 PDF 自动矫正标题恢复为 title_raw；默认 dry-run"

    def add_arguments(self, parser):
        parser.add_argument("--doi", action="append", default=[], help="只回滚指定 DOI，可重复")
        parser.add_argument("--keep-doi", action="append", default=[], help="保留的 DOI，可重复")
        parser.add_argument("--apply", action="store_true", help="实际回滚；默认只预览")

    def handle(self, *args, **opts):
        keep = [doi.strip().lower() for doi in opts["keep_doi"] if doi.strip()]
        selected = [doi.strip().lower() for doi in opts["doi"] if doi.strip()]
        qs = Paper.objects.filter(
            title_quality_status=Paper.TITLE_CORRECTED,
            title_source__in=("pdf_metadata", "pdf_first_page"),
            title_raw__isnull=False,
        ).exclude(title_raw="").order_by("id")
        if selected:
            qs = qs.filter(doi__in=selected)
        if keep:
            qs = qs.exclude(doi__in=keep)

        count = 0
        for paper in qs.iterator(chunk_size=500):
            count += 1
            self.stdout.write(
                f"[rollback] {paper.doi} {paper.title!r} -> {paper.title_raw!r}"
            )
            if not opts["apply"]:
                continue
            restored = paper.title_raw
            paper.title = restored
            paper.title_raw = None
            paper.title_source = None
            paper.title_quality_status = (
                Paper.TITLE_SUSPECT if assess_title(restored).suspect
                else Paper.TITLE_UNCHECKED
            )
            paper.title_verified_at = None
            paper.update_time = timezone.now()
            paper.save(update_fields=[
                "title", "title_raw", "title_source", "title_quality_status",
                "title_verified_at", "update_time",
            ])

        mode = "apply" if opts["apply"] else "dry-run"
        self.stdout.write(self.style.SUCCESS(f"完成({mode}) rollback={count}"))
