"""种子数据:无机非金属材料方向的期刊 / 关键词监控,并注册每周的监控周期任务。

- 8 本方向期刊(按 ISSN,OpenAlex 跨出版商都能抓)
- 若干英文搜索词(OpenAlex 语料是英文,中文词搜不到,故用英文;note 标注方向)
- 注册 PeriodicTask: apps.resm.tasks.monitor_papers,每天 05:00 跑一次
get_or_create / update_or_create 保证迁移可安全重跑。
"""
from django.db import migrations
from apps.utils.snowflake import idWorker

NOTE = "无机非金属材料"

JOURNALS = [
    ("0272-8842", "Ceramics International"),
    ("0955-2219", "Journal of the European Ceramic Society"),
    ("0008-8846", "Cement and Concrete Research"),
    ("0958-9465", "Cement and Concrete Composites"),
    ("0950-0618", "Construction and Building Materials"),
    ("0022-3093", "Journal of Non-Crystalline Solids"),
    ("0002-7820", "Journal of the American Ceramic Society"),
    ("0022-2461", "Journal of Materials Science"),
]

SEARCHES = [
    ("ceramics material", "陶瓷材料"),
    ("glass material", "玻璃材料"),
    ("cement", "水泥"),
    ("refractory material", "耐火材料"),
    ("crystalline material", "晶体材料"),
]

MONITOR_TASK = "apps.resm.tasks.monitor_papers"
MONITOR_NAME = "resm: 论文监控(期刊/关键词)"


def seed(apps, schema_editor):
    PaperMonitor = apps.get_model("resm", "PaperMonitor")
    for issn, name in JOURNALS:
        PaperMonitor.objects.get_or_create(
            type="journal", value=issn,
            defaults={"id": idWorker.get_id(), "name": name, "note": NOTE,
                      "is_active": True, "days": 7},
        )
    for term, name in SEARCHES:
        PaperMonitor.objects.get_or_create(
            type="search", value=term,
            defaults={"id": idWorker.get_id(), "name": name, "note": NOTE,
                      "is_active": True, "days": 7},
        )

    CrontabSchedule = apps.get_model("django_celery_beat", "CrontabSchedule")
    PeriodicTask = apps.get_model("django_celery_beat", "PeriodicTask")
    sched, _ = CrontabSchedule.objects.get_or_create(
        minute="0", hour="5", day_of_week="*", day_of_month="*", month_of_year="*",
    )
    PeriodicTask.objects.update_or_create(
        name=MONITOR_NAME,
        defaults={
            "task": MONITOR_TASK,
            "crontab": sched,
            "interval": None,
            "enabled": True,
            "description": "每天 05:00 拉取监控期刊/关键词的最新论文元数据(OpenAlex,跨出版商)",
        },
    )


def unseed(apps, schema_editor):
    PaperMonitor = apps.get_model("resm", "PaperMonitor")
    PaperMonitor.objects.filter(type="journal", value__in=[i for i, _ in JOURNALS]).delete()
    PaperMonitor.objects.filter(type="search", value__in=[t for t, _ in SEARCHES]).delete()
    PeriodicTask = apps.get_model("django_celery_beat", "PeriodicTask")
    PeriodicTask.objects.filter(name=MONITOR_NAME).delete()


class Migration(migrations.Migration):

    dependencies = [
        ("resm", "0008_papermonitor"),
        ("django_celery_beat", "__latest__"),
    ]

    operations = [
        migrations.RunPython(seed, unseed),
    ]
