from django.db import migrations, models


PLAYER_RATING_FIELDS = (
    "overall",
    "potential",
    "pace",
    "acceleration",
    "agility",
    "balance",
    "strength",
    "stamina",
    "jumping",
    "natural_fitness",
    "ball_control",
    "dribbling",
    "passing",
    "crossing",
    "finishing",
    "shooting",
    "long_shots",
    "first_touch",
    "heading",
    "tackling",
    "marking",
    "set_pieces",
    "vision",
    "positioning",
    "decision_making",
    "composure",
    "concentration",
    "anticipation",
    "off_ball",
    "aggression",
    "work_rate",
    "teamwork",
    "gk_diving",
    "gk_handling",
    "gk_reflexes",
    "gk_positioning",
    "gk_kicking",
    "gk_one_on_one",
)


def rating_range_condition():
    condition = models.Q()
    for field_name in PLAYER_RATING_FIELDS:
        condition &= models.Q(
            **{
                f"{field_name}__gte": 1,
                f"{field_name}__lte": 100,
            }
        )
    return condition


def validate_existing_players(apps, schema_editor):
    Player = apps.get_model("players", "Player")

    valid_tiers = ["AMATEUR", "NORMAL", "PROFESSIONAL", "SUPERSTAR"]
    valid_positions = [
        "GK", "CB", "LB", "RB", "CDM", "CM", "CAM",
        "LM", "RM", "LW", "RW", "ST", "CF",
    ]

    invalid_identity = Player.objects.exclude(tier__in=valid_tiers).count()
    invalid_identity += Player.objects.exclude(position__in=valid_positions).count()

    invalid_ratings = models.Q()
    for field_name in PLAYER_RATING_FIELDS:
        invalid_ratings |= models.Q(**{f"{field_name}__lt": 1})
        invalid_ratings |= models.Q(**{f"{field_name}__gt": 100})

    invalid_rating_count = Player.objects.filter(invalid_ratings).count()
    invalid_potential_count = Player.objects.filter(
        potential__lt=models.F("overall")
    ).count()

    if invalid_identity or invalid_rating_count or invalid_potential_count:
        raise RuntimeError(
            "Cannot add Player integrity constraints because legacy Player "
            "rows violate the new domain invariants. Fix the data first. "
            f"invalid tier/position rows={invalid_identity}, "
            f"invalid rating rows={invalid_rating_count}, "
            f"potential<overall rows={invalid_potential_count}."
        )


class Migration(migrations.Migration):
    dependencies = [
        ("players", "0001_initial"),
    ]

    operations = [
        migrations.RunPython(
            validate_existing_players,
            migrations.RunPython.noop,
        ),
        migrations.AddConstraint(
            model_name="player",
            constraint=models.CheckConstraint(
                condition=models.Q(
                    tier__in=[
                        "AMATEUR",
                        "NORMAL",
                        "PROFESSIONAL",
                        "SUPERSTAR",
                    ]
                ),
                name="player_valid_tier",
            ),
        ),
        migrations.AddConstraint(
            model_name="player",
            constraint=models.CheckConstraint(
                condition=models.Q(
                    position__in=[
                        "GK",
                        "CB",
                        "LB",
                        "RB",
                        "CDM",
                        "CM",
                        "CAM",
                        "LM",
                        "RM",
                        "LW",
                        "RW",
                        "ST",
                        "CF",
                    ]
                ),
                name="player_valid_position",
            ),
        ),
        migrations.AddConstraint(
            model_name="player",
            constraint=models.CheckConstraint(
                condition=rating_range_condition(),
                name="player_ratings_1_100",
            ),
        ),
        migrations.AddConstraint(
            model_name="player",
            constraint=models.CheckConstraint(
                condition=models.Q(potential__gte=models.F("overall")),
                name="player_potential_gte_overall",
            ),
        ),
    ]
