import hashlib
import json
import uuid
from datetime import timedelta

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


def backfill_scheduled_matchdays(apps, schema_editor):
    Match = apps.get_model("matches", "Match")
    Operation = apps.get_model("matches", "MatchdayOperation")
    TeamState = apps.get_model("matches", "MatchdayTeamState")
    Audit = apps.get_model("matches", "MatchdayAuditEvent")

    for match in (
        Match.objects.filter(status="SCHEDULED")
        .select_related("fixture")
        .exclude(scheduled_at__isnull=True)
        .iterator()
    ):
        kickoff = match.scheduled_at
        operation = Operation.objects.create(
            match_id=match.pk,
            profile_id=None,
            status="OPEN",
            lineup_deadline_minutes=60,
            checkin_open_minutes=120,
            checkin_deadline_minutes=15,
            max_delay_minutes=15,
            auto_start_enabled=True,
            lineup_deadline_at=kickoff - timedelta(minutes=60),
            checkin_opens_at=kickoff - timedelta(minutes=120),
            checkin_deadline_at=kickoff - timedelta(minutes=15),
            kickoff_at=kickoff,
            grace_deadline_at=kickoff + timedelta(minutes=15),
            policy_key="ftg.matchday.operations.v1",
            policy_version="1.0.0",
            schema_version=1,
        )
        TeamState.objects.create(operation_id=operation.pk, club_id=match.fixture.home_club_id)
        TeamState.objects.create(operation_id=operation.pk, club_id=match.fixture.away_club_id)
        payload = {
            "lineup_deadline_at": operation.lineup_deadline_at.isoformat(),
            "checkin_opens_at": operation.checkin_opens_at.isoformat(),
            "checkin_deadline_at": operation.checkin_deadline_at.isoformat(),
            "kickoff_at": operation.kickoff_at.isoformat(),
            "grace_deadline_at": operation.grace_deadline_at.isoformat(),
            "auto_start_enabled": True,
            "migration_backfill": True,
        }
        hash_payload = {
            "operation_id": str(operation.pk),
            "match_id": str(match.pk),
            "sequence": 1,
            "event_type": "PREPARED",
            "club_id": None,
            "payload": payload,
            "policy_key": operation.policy_key,
            "policy_version": operation.policy_version,
        }
        evidence_hash = hashlib.sha256(
            json.dumps(hash_payload, sort_keys=True, separators=(",", ":"), default=str).encode("utf-8")
        ).hexdigest()
        Audit.objects.create(
            operation_id=operation.pk,
            sequence=1,
            event_type="PREPARED",
            payload=payload,
            evidence_hash=evidence_hash,
        )


def noop_reverse(apps, schema_editor):
    pass


class Migration(migrations.Migration):
    dependencies = [
        ("matches", "0008_kickoff_scheduling_engine"),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name="MatchdayOperationsProfile",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("country", models.CharField(max_length=80)),
                ("lineup_deadline_minutes", models.PositiveSmallIntegerField(default=60)),
                ("checkin_open_minutes", models.PositiveSmallIntegerField(default=120)),
                ("checkin_deadline_minutes", models.PositiveSmallIntegerField(default=15)),
                ("max_delay_minutes", models.PositiveSmallIntegerField(default=15)),
                ("auto_start_enabled", models.BooleanField(default=True)),
                ("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="MatchdayOperation",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("status", models.CharField(choices=[("OPEN", "Lineup/check-in window open"), ("DEADLINE_PASSED", "Lineup deadline processed"), ("READY", "Both teams ready"), ("DELAYED", "Kickoff delayed"), ("NO_SHOW_REVIEW", "No-show / operator review required"), ("STARTED", "Match started"), ("CLOSED", "Match operation closed"), ("CANCELLED", "Match cancelled")], default="OPEN", max_length=24)),
                ("lineup_deadline_minutes", models.PositiveSmallIntegerField()),
                ("checkin_open_minutes", models.PositiveSmallIntegerField()),
                ("checkin_deadline_minutes", models.PositiveSmallIntegerField()),
                ("max_delay_minutes", models.PositiveSmallIntegerField()),
                ("auto_start_enabled", models.BooleanField(default=True)),
                ("lineup_deadline_at", models.DateTimeField()),
                ("checkin_opens_at", models.DateTimeField()),
                ("checkin_deadline_at", models.DateTimeField()),
                ("kickoff_at", models.DateTimeField()),
                ("grace_deadline_at", models.DateTimeField()),
                ("policy_key", models.CharField(max_length=100)),
                ("policy_version", models.CharField(max_length=30)),
                ("schema_version", models.PositiveSmallIntegerField(default=1)),
                ("prepared_at", models.DateTimeField(auto_now_add=True)),
                ("deadline_processed_at", models.DateTimeField(blank=True, null=True)),
                ("ready_at", models.DateTimeField(blank=True, null=True)),
                ("started_at", models.DateTimeField(blank=True, null=True)),
                ("closed_at", models.DateTimeField(blank=True, null=True)),
                ("updated_at", models.DateTimeField(auto_now=True)),
                ("match", models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name="matchday_operation", to="matches.match")),
                ("profile", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="operations", to="matches.matchdayoperationsprofile")),
            ],
            options={"ordering": ["kickoff_at", "match_id"]},
        ),
        migrations.CreateModel(
            name="PlayerMatchSuspension",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("reason", models.CharField(choices=[("DISCIPLINARY", "Disciplinary suspension"), ("RED_CARD", "Red-card suspension"), ("CARD_ACCUMULATION", "Card accumulation"), ("GOVERNANCE", "Governance decision"), ("OTHER", "Other")], max_length=24)),
                ("reason_text", models.CharField(blank=True, default="", max_length=500)),
                ("source_type", models.CharField(blank=True, default="", max_length=50)),
                ("source_id", models.CharField(blank=True, default="", max_length=100)),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("issued_by", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="issued_match_suspensions", to=settings.AUTH_USER_MODEL)),
                ("match", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="player_suspensions", to="matches.match")),
                ("player", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="match_suspensions", to="players.player")),
            ],
            options={"ordering": ["match_id", "player_id"]},
        ),
        migrations.CreateModel(
            name="MatchdayTeamState",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("attendance_status", models.CharField(choices=[("PENDING", "Pending check-in"), ("PRESENT", "Present on time"), ("LATE", "Late arrival"), ("NO_SHOW", "No show")], default="PENDING", max_length=12)),
                ("readiness_status", models.CharField(choices=[("PENDING", "Readiness pending"), ("READY", "Ready"), ("BLOCKED", "Blocked")], default="PENDING", max_length=12)),
                ("checked_in_at", models.DateTimeField(blank=True, null=True)),
                ("readiness_checked_at", models.DateTimeField(blank=True, null=True)),
                ("block_reason", models.CharField(blank=True, default="", max_length=500)),
                ("updated_at", models.DateTimeField(auto_now=True)),
                ("checked_in_by", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="matchday_checkins", to=settings.AUTH_USER_MODEL)),
                ("club", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="matchday_team_states", to="clubs.club")),
                ("operation", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name="team_states", to="matches.matchdayoperation")),
            ],
            options={"ordering": ["operation_id", "club_id"]},
        ),
        migrations.CreateModel(
            name="PlayerMatchSuspensionRevocation",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("reason_text", models.CharField(max_length=500)),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("revoked_by", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="revoked_match_suspensions", to=settings.AUTH_USER_MODEL)),
                ("suspension", models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name="revocation", to="matches.playermatchsuspension")),
            ],
        ),
        migrations.CreateModel(
            name="MatchdayEligibilityCheck",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("revision_number", models.PositiveSmallIntegerField()),
                ("eligible", models.BooleanField()),
                ("payload", models.JSONField()),
                ("evidence_hash", models.CharField(max_length=64)),
                ("policy_key", models.CharField(max_length=100)),
                ("policy_version", models.CharField(max_length=30)),
                ("schema_version", models.PositiveSmallIntegerField(default=1)),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("club", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="matchday_eligibility_checks", to="clubs.club")),
                ("operation", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="eligibility_checks", to="matches.matchdayoperation")),
            ],
            options={"ordering": ["operation_id", "club_id", "revision_number"]},
        ),
        migrations.CreateModel(
            name="MatchdayAuditEvent",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("sequence", models.PositiveSmallIntegerField()),
                ("event_type", models.CharField(choices=[("PREPARED", "Operation prepared"), ("SCHEDULE_REFRESHED", "Schedule refreshed"), ("LINEUP_DEADLINE", "Lineup deadline processed"), ("CHECKED_IN", "Team checked in"), ("READINESS_CHECKED", "Readiness checked"), ("DELAYED", "Kickoff delayed"), ("NO_SHOW", "No show detected"), ("AUTO_START", "Automatic start"), ("MANUAL_START_READY", "Manual start readiness verified"), ("STARTED", "Match started"), ("CANCELLED", "Operation cancelled"), ("CLOSED", "Operation closed")], max_length=24)),
                ("payload", models.JSONField(default=dict)),
                ("evidence_hash", models.CharField(max_length=64)),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("club", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="matchday_audit_events", to="clubs.club")),
                ("operation", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="audit_events", to="matches.matchdayoperation")),
                ("performed_by", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="matchday_audit_events", to=settings.AUTH_USER_MODEL)),
            ],
            options={"ordering": ["operation_id", "sequence"]},
        ),
        migrations.AddConstraint(
            model_name="matchdayoperationsprofile",
            constraint=models.UniqueConstraint(django.db.models.functions.Lower("country"), name="uq_matchday_profile_country_ci"),
        ),
        migrations.AddConstraint(model_name="matchdayoperationsprofile", constraint=models.CheckConstraint(condition=models.Q(("lineup_deadline_minutes__gte", 15), ("lineup_deadline_minutes__lte", 360)), name="matchday_lineup_dl_15_360")),
        migrations.AddConstraint(model_name="matchdayoperationsprofile", constraint=models.CheckConstraint(condition=models.Q(("checkin_open_minutes__gte", 30), ("checkin_open_minutes__lte", 360)), name="matchday_checkin_open_30_360")),
        migrations.AddConstraint(model_name="matchdayoperationsprofile", constraint=models.CheckConstraint(condition=models.Q(("checkin_deadline_minutes__gte", 0), ("checkin_deadline_minutes__lte", 120)), name="matchday_checkin_dl_0_120")),
        migrations.AddConstraint(model_name="matchdayoperationsprofile", constraint=models.CheckConstraint(condition=models.Q(("max_delay_minutes__gte", 0), ("max_delay_minutes__lte", 120)), name="matchday_delay_0_120")),
        migrations.AddConstraint(model_name="matchdayoperationsprofile", constraint=models.CheckConstraint(condition=models.Q(("checkin_open_minutes__gt", models.F("checkin_deadline_minutes"))), name="matchday_checkin_open_order")),
        migrations.AddConstraint(model_name="matchdayoperationsprofile", constraint=models.CheckConstraint(condition=models.Q(("lineup_deadline_minutes__gte", models.F("checkin_deadline_minutes"))), name="matchday_lineup_checkin_order")),
        migrations.AddConstraint(model_name="matchdayoperation", constraint=models.CheckConstraint(condition=models.Q(("status__in", ["OPEN", "DEADLINE_PASSED", "READY", "DELAYED", "NO_SHOW_REVIEW", "STARTED", "CLOSED", "CANCELLED"])), name="matchday_valid_status")),
        migrations.AddConstraint(model_name="matchdayoperation", constraint=models.CheckConstraint(condition=models.Q(("schema_version__gte", 1)), name="matchday_schema_gte_1")),
        migrations.AddConstraint(model_name="matchdayoperation", constraint=models.CheckConstraint(condition=models.Q(("checkin_opens_at__lte", models.F("checkin_deadline_at"))), name="matchday_checkin_open_order")),
        migrations.AddConstraint(model_name="matchdayoperation", constraint=models.CheckConstraint(condition=models.Q(("lineup_deadline_at__lte", models.F("checkin_deadline_at"))), name="matchday_lineup_deadline_order")),
        migrations.AddConstraint(model_name="matchdayoperation", constraint=models.CheckConstraint(condition=models.Q(("checkin_deadline_at__lte", models.F("kickoff_at"))), name="matchday_checkin_pre_kickoff")),
        migrations.AddConstraint(model_name="matchdayoperation", constraint=models.CheckConstraint(condition=models.Q(("kickoff_at__lte", models.F("grace_deadline_at"))), name="matchday_grace_after_kickoff")),
        migrations.AddConstraint(model_name="matchdayoperation", constraint=models.CheckConstraint(condition=~models.Q(("policy_key", "")), name="matchday_policy_key_nonempty")),
        migrations.AddConstraint(model_name="matchdayoperation", constraint=models.CheckConstraint(condition=~models.Q(("policy_version", "")), name="matchday_policy_ver_nonempty")),
        migrations.AddConstraint(model_name="matchdayteamstate", constraint=models.UniqueConstraint(fields=("operation", "club"), name="uq_matchday_operation_club")),
        migrations.AddConstraint(model_name="matchdayteamstate", constraint=models.CheckConstraint(condition=models.Q(("attendance_status__in", ["PENDING", "PRESENT", "LATE", "NO_SHOW"])), name="matchday_valid_attendance")),
        migrations.AddConstraint(model_name="matchdayteamstate", constraint=models.CheckConstraint(condition=models.Q(("readiness_status__in", ["PENDING", "READY", "BLOCKED"])), name="matchday_valid_readiness")),
        migrations.AddConstraint(model_name="playermatchsuspension", constraint=models.UniqueConstraint(fields=("match", "player"), name="uq_match_player_suspension")),
        migrations.AddConstraint(model_name="playermatchsuspension", constraint=models.CheckConstraint(condition=models.Q(("reason__in", ["DISCIPLINARY", "RED_CARD", "CARD_ACCUMULATION", "GOVERNANCE", "OTHER"])), name="match_suspension_valid_reason")),
        migrations.AddConstraint(model_name="matchdayeligibilitycheck", constraint=models.UniqueConstraint(fields=("operation", "club", "revision_number"), name="uq_matchday_elig_revision")),
        migrations.AddConstraint(model_name="matchdayeligibilitycheck", constraint=models.CheckConstraint(condition=models.Q(("revision_number__gte", 1)), name="matchday_elig_rev_gte_1")),
        migrations.AddConstraint(model_name="matchdayeligibilitycheck", constraint=models.CheckConstraint(condition=~models.Q(("evidence_hash", "")), name="matchday_elig_hash_nonempty")),
        migrations.AddConstraint(model_name="matchdayauditevent", constraint=models.UniqueConstraint(fields=("operation", "sequence"), name="uq_matchday_audit_sequence")),
        migrations.AddConstraint(model_name="matchdayauditevent", constraint=models.CheckConstraint(condition=models.Q(("sequence__gte", 1)), name="matchday_audit_seq_gte_1")),
        migrations.AddConstraint(model_name="matchdayauditevent", constraint=models.CheckConstraint(condition=models.Q(("event_type__in", ["PREPARED", "SCHEDULE_REFRESHED", "LINEUP_DEADLINE", "CHECKED_IN", "READINESS_CHECKED", "DELAYED", "NO_SHOW", "AUTO_START", "MANUAL_START_READY", "STARTED", "CANCELLED", "CLOSED"])), name="matchday_audit_valid_type")),
        migrations.AddConstraint(model_name="matchdayauditevent", constraint=models.CheckConstraint(condition=~models.Q(("evidence_hash", "")), name="matchday_audit_hash_nonempty")),
        migrations.AddIndex(model_name="matchdayoperation", index=models.Index(fields=["status", "kickoff_at"], name="matchday_status_kickoff_idx")),
        migrations.AddIndex(model_name="matchdayoperation", index=models.Index(fields=["lineup_deadline_at"], name="matchday_lineup_deadline_idx")),
        migrations.AddIndex(model_name="matchdayoperation", index=models.Index(fields=["grace_deadline_at"], name="matchday_grace_deadline_idx")),
        migrations.AddIndex(model_name="matchdayteamstate", index=models.Index(fields=["operation", "readiness_status"], name="matchday_team_ready_idx")),
        migrations.AddIndex(model_name="matchdayteamstate", index=models.Index(fields=["club", "attendance_status"], name="matchday_club_attend_idx")),
        migrations.AddIndex(model_name="playermatchsuspension", index=models.Index(fields=["match", "player"], name="match_susp_match_player_idx")),
        migrations.RunPython(backfill_scheduled_matchdays, noop_reverse),
    ]
