import django.db.models.deletion
import django.db.models.functions
import uuid
from django.conf import settings
from django.db import migrations, models


def backfill_existing_schedule_revisions(apps, schema_editor):
    import hashlib
    import json

    Match = apps.get_model("matches", "Match")
    Revision = apps.get_model("matches", "MatchScheduleRevision")
    for match in Match.objects.exclude(scheduled_at__isnull=True).iterator():
        scheduled_at = match.scheduled_at
        tz_name = getattr(scheduled_at.tzinfo, "key", None) or str(scheduled_at.tzinfo or "UTC")
        payload = {
            "match_id": str(match.pk),
            "revision_number": 1,
            "calendar_slot_id": None,
            "previous_scheduled_at": None,
            "scheduled_at": scheduled_at.isoformat(),
            "timezone_name": tz_name,
            "reason": "INITIAL",
            "reason_text": "Migration backfill of pre-existing authoritative kickoff.",
            "policy_key": "ftg.match.kickoff_scheduling.v1",
            "policy_version": "1.0.0",
            "schema_version": 1,
        }
        evidence_hash = hashlib.sha256(
            json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str).encode("utf-8")
        ).hexdigest()
        Revision.objects.create(
            match_id=match.pk,
            revision_number=1,
            previous_scheduled_at=None,
            scheduled_at=scheduled_at,
            timezone_name=tz_name,
            reason="INITIAL",
            reason_text="Migration backfill of pre-existing authoritative kickoff.",
            policy_key="ftg.match.kickoff_scheduling.v1",
            policy_version="1.0.0",
            schema_version=1,
            evidence_hash=evidence_hash,
        )


def noop_reverse(apps, schema_editor):
    pass


class Migration(migrations.Migration):
    dependencies = [
        ("matches", "0007_federation_fixture_leg_semantics"),
        ("seasons", "0003_season_competition_orchestration"),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name="CountrySchedulingProfile",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("country", models.CharField(max_length=80)),
                ("timezone_name", models.CharField(max_length=64)),
                ("adult_kickoff_time", models.TimeField(default="18:00:00")),
                ("youth_kickoff_time", models.TimeField(default="15:00:00")),
                ("cup_kickoff_time", models.TimeField(default="19:00:00")),
                ("continental_kickoff_time", models.TimeField(default="20:00:00")),
                ("min_rest_hours", models.PositiveSmallIntegerField(default=72)),
                ("max_auto_shift_days", models.PositiveSmallIntegerField(default=7)),
                ("is_active", models.BooleanField(default=True)),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("updated_at", models.DateTimeField(auto_now=True)),
            ],
            options={"ordering": ["country"]},
        ),
        migrations.CreateModel(
            name="ClubHomeStadium",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("name", models.CharField(max_length=140)),
                ("timezone_name", models.CharField(blank=True, default="", max_length=64)),
                ("kickoff_time_override", models.TimeField(blank=True, null=True)),
                ("is_active", models.BooleanField(default=True)),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("updated_at", models.DateTimeField(auto_now=True)),
                ("club", models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name="home_stadium_profile", to="clubs.club")),
            ],
            options={"ordering": ["club__name"]},
        ),
        migrations.CreateModel(
            name="MatchScheduleRevision",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("revision_number", models.PositiveSmallIntegerField()),
                ("previous_scheduled_at", models.DateTimeField(blank=True, null=True)),
                ("scheduled_at", models.DateTimeField()),
                ("timezone_name", models.CharField(max_length=64)),
                ("reason", models.CharField(choices=[("INITIAL", "Initial scheduling"), ("CONFLICT_SHIFT", "Automatic conflict shift"), ("PROGRESSION", "Competition progression scheduling"), ("MANUAL", "Manual reschedule")], max_length=20)),
                ("reason_text", models.CharField(blank=True, default="", max_length=500)),
                ("policy_key", models.CharField(max_length=100)),
                ("policy_version", models.CharField(max_length=30)),
                ("schema_version", models.PositiveSmallIntegerField(default=1)),
                ("evidence_hash", models.CharField(max_length=64)),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("calendar_slot", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="match_schedule_revisions", to="seasons.seasoncompetitioncalendarslot")),
                ("match", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="schedule_revisions", to="matches.match")),
                ("performed_by", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="match_schedule_revisions", to=settings.AUTH_USER_MODEL)),
            ],
            options={"ordering": ["match_id", "revision_number"]},
        ),
        migrations.RunPython(backfill_existing_schedule_revisions, noop_reverse),
        migrations.AddConstraint(
            model_name="countryschedulingprofile",
            constraint=models.UniqueConstraint(django.db.models.functions.Lower("country"), name="uq_country_sched_country_ci"),
        ),
        migrations.AddConstraint(
            model_name="countryschedulingprofile",
            constraint=models.CheckConstraint(condition=models.Q(("min_rest_hours__gte", 24), ("min_rest_hours__lte", 168)), name="country_sched_rest_24_168"),
        ),
        migrations.AddConstraint(
            model_name="countryschedulingprofile",
            constraint=models.CheckConstraint(condition=models.Q(("max_auto_shift_days__gte", 0), ("max_auto_shift_days__lte", 14)), name="country_sched_shift_0_14"),
        ),
        migrations.AddConstraint(
            model_name="matchschedulerevision",
            constraint=models.UniqueConstraint(fields=("match", "revision_number"), name="uq_match_schedule_revision_no"),
        ),
        migrations.AddConstraint(
            model_name="matchschedulerevision",
            constraint=models.CheckConstraint(condition=models.Q(("revision_number__gte", 1)), name="match_sched_rev_gte_1"),
        ),
        migrations.AddConstraint(
            model_name="matchschedulerevision",
            constraint=models.CheckConstraint(condition=models.Q(("schema_version__gte", 1)), name="match_sched_schema_gte_1"),
        ),
        migrations.AddConstraint(
            model_name="matchschedulerevision",
            constraint=models.CheckConstraint(condition=~models.Q(("evidence_hash", "")), name="match_sched_hash_nonempty"),
        ),
        migrations.AddIndex(
            model_name="matchschedulerevision",
            index=models.Index(fields=["match", "created_at"], name="match_sched_match_idx"),
        ),
        migrations.AddIndex(
            model_name="matchschedulerevision",
            index=models.Index(fields=["scheduled_at"], name="match_sched_time_idx"),
        ),
    ]
