import uuid

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


def backfill_match_result_type(apps, schema_editor):
    Match = apps.get_model("matches", "Match")
    Match.objects.filter(status="COMPLETED").update(result_type="PLAYED")


def reverse_match_result_type(apps, schema_editor):
    Match = apps.get_model("matches", "Match")
    Match.objects.update(result_type="NONE")


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

    operations = [
        migrations.AddField(
            model_name="match",
            name="result_type",
            field=models.CharField(
                choices=[
                    ("NONE", "No result"),
                    ("PLAYED", "Played result"),
                    ("ADMINISTRATIVE", "Administrative result"),
                ],
                default="NONE",
                max_length=16,
            ),
        ),
        migrations.RunPython(backfill_match_result_type, reverse_match_result_type),
        migrations.RemoveConstraint(model_name="match", name="match_lifecycle"),
        migrations.AddConstraint(
            model_name="match",
            constraint=models.CheckConstraint(
                condition=(
                    models.Q(
                        status="PENDING", scheduled_at__isnull=True, started_at__isnull=True,
                        completed_at__isnull=True, cancelled_at__isnull=True,
                        home_score__isnull=True, away_score__isnull=True, result_type="NONE",
                    )
                    | models.Q(
                        status="SCHEDULED", scheduled_at__isnull=False, started_at__isnull=True,
                        completed_at__isnull=True, cancelled_at__isnull=True,
                        home_score__isnull=True, away_score__isnull=True, result_type="NONE",
                    )
                    | models.Q(
                        status="IN_PROGRESS", scheduled_at__isnull=False, started_at__isnull=False,
                        completed_at__isnull=True, cancelled_at__isnull=True,
                        home_score__isnull=True, away_score__isnull=True, result_type="NONE",
                    )
                    | models.Q(
                        status="COMPLETED", scheduled_at__isnull=False, started_at__isnull=False,
                        completed_at__isnull=False, cancelled_at__isnull=True,
                        home_score__isnull=False, away_score__isnull=False, result_type="PLAYED",
                    )
                    | models.Q(
                        status="COMPLETED", scheduled_at__isnull=False, started_at__isnull=True,
                        completed_at__isnull=False, cancelled_at__isnull=True,
                        home_score__isnull=False, away_score__isnull=False,
                        result_type="ADMINISTRATIVE",
                    )
                    | models.Q(
                        status="CANCELLED", started_at__isnull=True,
                        completed_at__isnull=True, cancelled_at__isnull=False,
                        home_score__isnull=True, away_score__isnull=True, result_type="NONE",
                    )
                ),
                name="match_lifecycle",
            ),
        ),
        migrations.AlterField(
            model_name="matchdayauditevent",
            name="event_type",
            field=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"),
                    ("ADMINISTRATIVE_RESULT", "Administrative result applied"),
                    ("CANCELLED", "Operation cancelled"),
                    ("CLOSED", "Operation closed"),
                ],
                max_length=24,
            ),
        ),
        migrations.RemoveConstraint(
            model_name="matchdayauditevent", name="matchday_audit_valid_type"
        ),
        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",
                        "ADMINISTRATIVE_RESULT", "CANCELLED", "CLOSED",
                    ]
                ),
                name="matchday_audit_valid_type",
            ),
        ),
        migrations.CreateModel(
            name="CompetitionDisciplineProfile",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("yellow_threshold", models.PositiveSmallIntegerField(default=3)),
                ("yellow_suspension_matches", models.PositiveSmallIntegerField(default=1)),
                ("direct_red_suspension_matches", models.PositiveSmallIntegerField(default=1)),
                ("second_yellow_suspension_matches", models.PositiveSmallIntegerField(default=1)),
                ("second_yellow_counts_toward_accumulation", models.BooleanField(default=False)),
                ("forfeit_score_for", models.PositiveSmallIntegerField(default=3)),
                ("forfeit_score_against", models.PositiveSmallIntegerField(default=0)),
                ("auto_no_show_forfeit", 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)),
                ("federation_competition", models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="discipline_profile", to="federations.federationcompetition")),
                ("league_competition", models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="discipline_profile", to="leagues.leaguecompetition")),
            ],
        ),
        migrations.CreateModel(
            name="DisciplinaryCardEvent",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("sequence", models.PositiveSmallIntegerField()),
                ("minute", models.PositiveSmallIntegerField()),
                ("card_type", models.CharField(choices=[("YELLOW", "Yellow card"), ("SECOND_YELLOW", "Second-yellow dismissal"), ("DIRECT_RED", "Direct red card")], max_length=20)),
                ("source", models.CharField(choices=[("REFEREE", "Referee / official report"), ("MATCH_ENGINE", "Match engine"), ("GOVERNANCE", "Governance correction")], default="REFEREE", max_length=20)),
                ("evidence_hash", models.CharField(max_length=64)),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("club", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="disciplinary_cards", to="clubs.club")),
                ("match", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="disciplinary_cards", to="matches.match")),
                ("player", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="disciplinary_cards", to="players.player")),
                ("recorded_by", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="recorded_disciplinary_cards", to=settings.AUTH_USER_MODEL)),
                ("source_match_event", models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="disciplinary_card", to="matches.matchevent")),
            ],
            options={"ordering": ["match_id", "sequence"]},
        ),
        migrations.CreateModel(
            name="DisciplinaryCardRevocation",
            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)),
                ("card", models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name="revocation", to="matches.disciplinarycardevent")),
                ("revoked_by", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="revoked_disciplinary_cards", to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name="PlayerDisciplinarySanction",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("sanction_type", models.CharField(choices=[("DIRECT_RED", "Direct-red suspension"), ("SECOND_YELLOW", "Second-yellow suspension"), ("YELLOW_ACCUMULATION", "Yellow-card accumulation suspension"), ("GOVERNANCE", "Governance suspension")], max_length=24)),
                ("matches_total", models.PositiveSmallIntegerField()),
                ("semantic_key", models.CharField(max_length=180, unique=True)),
                ("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)),
                ("club_at_issue", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="player_disciplinary_sanctions", to="clubs.club")),
                ("federation_competition", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="player_disciplinary_sanctions", to="federations.federationcompetition")),
                ("issued_by", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="issued_disciplinary_sanctions", to=settings.AUTH_USER_MODEL)),
                ("league_competition", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="player_disciplinary_sanctions", to="leagues.leaguecompetition")),
                ("player", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="disciplinary_sanctions", to="players.player")),
                ("source_card", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="sanctions", to="matches.disciplinarycardevent")),
                ("source_match", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="issued_disciplinary_sanctions", to="matches.match")),
            ],
            options={"ordering": ["created_at", "id"]},
        ),
        migrations.CreateModel(
            name="DisciplinarySuspensionAssignment",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("ordinal", models.PositiveSmallIntegerField()),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("sanction", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="assignments", to="matches.playerdisciplinarysanction")),
                ("suspension", models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name="discipline_assignment", to="matches.playermatchsuspension")),
            ],
            options={"ordering": ["sanction_id", "ordinal"]},
        ),
        migrations.CreateModel(
            name="DisciplinarySanctionRevocation",
            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_disciplinary_sanctions", to=settings.AUTH_USER_MODEL)),
                ("sanction", models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name="revocation", to="matches.playerdisciplinarysanction")),
            ],
        ),
        migrations.CreateModel(
            name="DisciplinaryAppeal",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("reason_text", models.CharField(max_length=1000)),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("sanction", models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name="appeal", to="matches.playerdisciplinarysanction")),
                ("submitted_by", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="submitted_disciplinary_appeals", to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name="DisciplinaryAppealDecision",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("outcome", models.CharField(choices=[("UPHELD", "Appeal upheld"), ("REJECTED", "Appeal rejected")], max_length=12)),
                ("reason_text", models.CharField(max_length=1000)),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("appeal", models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name="decision", to="matches.disciplinaryappeal")),
                ("decided_by", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="disciplinary_appeal_decisions", to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name="DisciplineProcessingRun",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("card_count", models.PositiveSmallIntegerField(default=0)),
                ("sanction_count", models.PositiveSmallIntegerField(default=0)),
                ("policy_payload", models.JSONField(default=dict)),
                ("evidence_payload", models.JSONField(default=dict)),
                ("evidence_hash", models.CharField(max_length=64)),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("match", models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name="discipline_processing_run", to="matches.match")),
                ("processed_by", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="discipline_processing_runs", to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name="MatchAdministrativeDecision",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("reason", models.CharField(choices=[("NO_SHOW", "No-show forfeiture"), ("INELIGIBLE_PLAYER", "Ineligible player"), ("GOVERNANCE", "Governance decision")], max_length=24)),
                ("outcome", models.CharField(choices=[("HOME_FORFEIT", "Home club forfeits"), ("AWAY_FORFEIT", "Away club forfeits")], max_length=16)),
                ("home_score", models.PositiveSmallIntegerField()),
                ("away_score", models.PositiveSmallIntegerField()),
                ("reason_text", models.CharField(blank=True, default="", max_length=1000)),
                ("policy_payload", models.JSONField(default=dict)),
                ("evidence_hash", models.CharField(max_length=64)),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("decided_by", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="match_administrative_decisions", to=settings.AUTH_USER_MODEL)),
                ("match", models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name="administrative_decision", to="matches.match")),
            ],
        ),
        migrations.AddConstraint(
            model_name="competitiondisciplineprofile",
            constraint=models.CheckConstraint(
                condition=(
                    models.Q(league_competition__isnull=False, federation_competition__isnull=True)
                    | models.Q(league_competition__isnull=True, federation_competition__isnull=False)
                ), name="discipline_profile_exactly_one_comp"
            ),
        ),
        migrations.AddConstraint(model_name="competitiondisciplineprofile", constraint=models.CheckConstraint(condition=models.Q(yellow_threshold__gte=1), name="discipline_yellow_threshold_gte_1")),
        migrations.AddConstraint(model_name="competitiondisciplineprofile", constraint=models.CheckConstraint(condition=models.Q(yellow_suspension_matches__gte=1), name="discipline_yellow_ban_gte_1")),
        migrations.AddConstraint(model_name="competitiondisciplineprofile", constraint=models.CheckConstraint(condition=models.Q(direct_red_suspension_matches__gte=1), name="discipline_red_ban_gte_1")),
        migrations.AddConstraint(model_name="competitiondisciplineprofile", constraint=models.CheckConstraint(condition=models.Q(second_yellow_suspension_matches__gte=1), name="discipline_second_yellow_ban_gte_1")),
        migrations.AddConstraint(model_name="competitiondisciplineprofile", constraint=models.CheckConstraint(condition=models.Q(forfeit_score_for__gt=models.F("forfeit_score_against")), name="discipline_forfeit_winner_gt_loser")),
        migrations.AddConstraint(model_name="disciplinarycardevent", constraint=models.UniqueConstraint(fields=("match", "sequence"), name="uq_discipline_card_sequence")),
        migrations.AddConstraint(model_name="disciplinarycardevent", constraint=models.CheckConstraint(condition=models.Q(sequence__gte=1), name="discipline_card_seq_gte_1")),
        migrations.AddConstraint(model_name="disciplinarycardevent", constraint=models.CheckConstraint(condition=models.Q(minute__gte=1, minute__lte=120), name="discipline_card_minute_1_120")),
        migrations.AddConstraint(model_name="disciplinarycardevent", constraint=models.CheckConstraint(condition=models.Q(card_type__in=["YELLOW", "SECOND_YELLOW", "DIRECT_RED"]), name="discipline_card_valid_type")),
        migrations.AddConstraint(model_name="disciplinarycardevent", constraint=models.CheckConstraint(condition=models.Q(source__in=["REFEREE", "MATCH_ENGINE", "GOVERNANCE"]), name="discipline_card_valid_source")),
        migrations.AddConstraint(model_name="disciplinarycardevent", constraint=models.CheckConstraint(condition=~models.Q(evidence_hash=""), name="discipline_card_hash_nonempty")),
        migrations.AddIndex(model_name="disciplinarycardevent", index=models.Index(fields=["player", "match"], name="discipline_card_player_match_idx")),
        migrations.AddIndex(model_name="disciplinarycardevent", index=models.Index(fields=["club", "match"], name="discipline_card_club_match_idx")),
        migrations.AddConstraint(
            model_name="playerdisciplinarysanction",
            constraint=models.CheckConstraint(
                condition=(
                    models.Q(league_competition__isnull=False, federation_competition__isnull=True)
                    | models.Q(league_competition__isnull=True, federation_competition__isnull=False)
                ), name="discipline_sanction_exactly_one_comp"
            ),
        ),
        migrations.AddConstraint(model_name="playerdisciplinarysanction", constraint=models.CheckConstraint(condition=models.Q(sanction_type__in=["DIRECT_RED", "SECOND_YELLOW", "YELLOW_ACCUMULATION", "GOVERNANCE"]), name="discipline_sanction_valid_type")),
        migrations.AddConstraint(model_name="playerdisciplinarysanction", constraint=models.CheckConstraint(condition=models.Q(matches_total__gte=1), name="discipline_sanction_matches_gte_1")),
        migrations.AddConstraint(model_name="playerdisciplinarysanction", constraint=models.CheckConstraint(condition=~models.Q(semantic_key=""), name="discipline_sanction_key_nonempty")),
        migrations.AddConstraint(model_name="playerdisciplinarysanction", constraint=models.CheckConstraint(condition=~models.Q(evidence_hash=""), name="discipline_sanction_hash_nonempty")),
        migrations.AddIndex(model_name="playerdisciplinarysanction", index=models.Index(fields=["player", "league_competition"], name="discipline_sanction_player_league_idx")),
        migrations.AddIndex(model_name="playerdisciplinarysanction", index=models.Index(fields=["player", "federation_competition"], name="discipline_sanction_player_fed_idx")),
        migrations.AddConstraint(model_name="disciplinarysuspensionassignment", constraint=models.UniqueConstraint(fields=("sanction", "ordinal"), name="uq_discipline_sanction_assignment_ord")),
        migrations.AddConstraint(model_name="disciplinarysuspensionassignment", constraint=models.CheckConstraint(condition=models.Q(ordinal__gte=1), name="discipline_assignment_ord_gte_1")),
        migrations.AddConstraint(model_name="disciplinaryappealdecision", constraint=models.CheckConstraint(condition=models.Q(outcome__in=["UPHELD", "REJECTED"]), name="discipline_appeal_valid_outcome")),
        migrations.AddConstraint(model_name="disciplineprocessingrun", constraint=models.CheckConstraint(condition=~models.Q(evidence_hash=""), name="discipline_run_hash_nonempty")),
        migrations.AddConstraint(model_name="matchadministrativedecision", constraint=models.CheckConstraint(condition=models.Q(reason__in=["NO_SHOW", "INELIGIBLE_PLAYER", "GOVERNANCE"]), name="admin_decision_valid_reason")),
        migrations.AddConstraint(model_name="matchadministrativedecision", constraint=models.CheckConstraint(condition=models.Q(outcome__in=["HOME_FORFEIT", "AWAY_FORFEIT"]), name="admin_decision_valid_outcome")),
        migrations.AddConstraint(model_name="matchadministrativedecision", constraint=models.CheckConstraint(condition=~models.Q(evidence_hash=""), name="admin_decision_hash_nonempty")),
    ]
