import calendar
import hashlib
import random
from decimal import Decimal, ROUND_HALF_UP
from datetime import date, timedelta

from django.utils import timezone

from careers.models import CareerStatus, CareerType
from .constants import (
    ALL_ATTRIBUTES,
    POSITION_PRIMARY_ATTRIBUTES,
    POSITION_WEIGHTS,
    TIER_RANGES,
)
from .exceptions import (
    CareerRequiredError,
    InactiveCareerError,
    InvalidCareerTypeError,
    InvalidPlayerPositionError,
    InvalidPlayerTierError,
    PlayerAlreadyExistsError,
)
from .models import Player, PlayerTier, Position
from .validators import normalize_identity_text


class _StableProfileStream:
    """Deterministic integer stream for externally sourced player profiles."""

    def __init__(self, seed: str):
        self._seed = str(seed).encode("utf-8")
        self._counter = 0

    def randint(self, low: int, high: int) -> int:
        if high < low:
            raise ValueError("Invalid deterministic range.")
        payload = self._seed + b"|" + str(self._counter).encode("ascii")
        self._counter += 1
        value = int.from_bytes(hashlib.sha256(payload).digest()[:8], "big")
        return low + (value % (high - low + 1))


class PlayerGenerator:
    """
    Generates a new player with controlled randomness.

    PlayerCreationService is the authoritative application entry-point.
    Generator validation is intentionally defensive so direct internal use
    cannot bypass Career type/status or duplicate-player invariants.
    """

    MIN_AGE = 15
    MAX_AGE = 18

    @classmethod
    def generate(
        cls,
        *,
        career,
        first_name: str,
        last_name: str,
        nationality: str,
        position: Position,
        tier: PlayerTier,
        regional_federation=None,
    ) -> Player:
        if career is None:
            raise CareerRequiredError("Career is required.")

        cls._validate_tier(tier)
        cls._validate_position(position)

        if career.career_type != CareerType.PLAYER:
            raise InvalidCareerTypeError(
                "Only a PLAYER career can have a player."
            )

        if career.status != CareerStatus.ACTIVE:
            raise InactiveCareerError(
                "Only an ACTIVE career can have a player."
            )

        if Player.objects.filter(career_id=career.pk).exists():
            raise PlayerAlreadyExistsError(
                "This career already has a player."
            )

        age = random.randint(cls.MIN_AGE, cls.MAX_AGE)

        overall_min, overall_max = TIER_RANGES[tier]["overall"]
        potential_min, potential_max = TIER_RANGES[tier]["potential"]

        overall_target = random.randint(overall_min, overall_max)

        potential_low = max(potential_min, overall_target)
        potential_high = max(potential_low, potential_max)
        potential = random.randint(potential_low, potential_high)

        attributes = cls._generate_attributes(
            position=position,
            target_overall=overall_target,
        )

        # Preserve attribute randomness while normalizing the *actual* weighted
        # OVR into the selected tier. The unnormalized weighted average could
        # otherwise fall below the footballer baseline even with target >=50.
        attributes = cls._normalize_generated_attributes(
            position=position, attributes=attributes, target_overall=overall_target,
        )
        overall = cls._calculate_overall(position=position, attributes=attributes)
        if overall != overall_target:
            raise RuntimeError("Generated rating normalization failed.")

        # Potential is a ceiling and therefore must never start below current
        # capability, even if weighted attribute generation moves final overall.
        potential = max(potential, overall)

        date_of_birth = cls._generate_birth_date(age)
        from federations.region_selection import player_region
        region = player_region(nationality=nationality, preferred=regional_federation)

        return Player.objects.create(
            career=career,
            regional_federation=region,
            first_name=normalize_identity_text(
                first_name, field_name="first_name"
            ),
            last_name=normalize_identity_text(
                last_name, field_name="last_name"
            ),
            date_of_birth=date_of_birth,
            nationality=normalize_identity_text(
                nationality, field_name="nationality"
            ),
            tier=tier,
            position=position,
            overall=overall,
            potential=potential,
            **attributes,
        )

    @classmethod
    def generate_from_profile(
        cls,
        *,
        career,
        first_name: str,
        last_name: str,
        date_of_birth: date,
        nationality: str,
        position: Position,
        tier: PlayerTier,
        overall_target: int,
        potential: int,
        deterministic_seed: str,
        regional_federation=None,
    ) -> Player:
        """Create a Player from an authoritative external football profile.

        This path is used by Academy claim.  Identity and DOB are preserved,
        while granular ratings are generated deterministically inside the
        Player domain.  The weighted overall is normalized to the requested
        target so Academy estimates do not drift during claim.
        """
        if career is None:
            raise CareerRequiredError("Career is required.")
        cls._validate_tier(tier)
        cls._validate_position(position)
        if career.career_type != CareerType.PLAYER:
            raise InvalidCareerTypeError("Only a PLAYER career can have a player.")
        if career.status != CareerStatus.ACTIVE:
            raise InactiveCareerError("Only an ACTIVE career can have a player.")
        if Player.objects.filter(career_id=career.pk).exists():
            raise PlayerAlreadyExistsError("This career already has a player.")
        if not isinstance(date_of_birth, date):
            raise ValueError("date_of_birth must be a date.")
        today = timezone.localdate()
        if date_of_birth > today:
            raise ValueError("date_of_birth cannot be in the future.")
        age = today.year - date_of_birth.year - (
            (today.month, today.day) < (date_of_birth.month, date_of_birth.day)
        )
        if not cls.MIN_AGE <= age <= cls.MAX_AGE:
            raise ValueError(
                f"Player creation age must be between {cls.MIN_AGE} and {cls.MAX_AGE}."
            )
        if not isinstance(overall_target, int) or not 50 <= overall_target <= 100:
            raise ValueError("overall_target must be between 50 and 100.")
        if not isinstance(potential, int) or not 1 <= potential <= 100:
            raise ValueError("potential must be between 1 and 100.")
        if potential < overall_target:
            raise ValueError("potential cannot be below overall_target.")

        attributes = cls._generate_profile_attributes(
            position=position,
            target_overall=overall_target,
            seed=deterministic_seed,
        )
        overall = cls._calculate_overall(position=position, attributes=attributes)
        if overall != overall_target:
            raise RuntimeError("Profile rating normalization failed.")
        from federations.region_selection import player_region
        region = player_region(nationality=nationality, preferred=regional_federation)

        return Player.objects.create(
            career=career,
            regional_federation=region,
            first_name=normalize_identity_text(first_name, field_name="first_name"),
            last_name=normalize_identity_text(last_name, field_name="last_name"),
            date_of_birth=date_of_birth,
            nationality=normalize_identity_text(nationality, field_name="nationality"),
            tier=tier,
            position=position,
            overall=overall,
            potential=potential,
            **attributes,
        )

    @classmethod
    def _generate_profile_attributes(
        cls, *, position: Position, target_overall: int, seed: str
    ) -> dict[str, int]:
        stream = _StableProfileStream(seed)
        weights = POSITION_WEIGHTS.get(position, {})
        primary_attributes = POSITION_PRIMARY_ATTRIBUTES.get(position, ())
        attributes: dict[str, int] = {}
        for attribute in ALL_ATTRIBUTES:
            weight = weights.get(attribute, 1.0)
            if attribute in primary_attributes:
                base = target_overall + stream.randint(0, 10)
            else:
                base = target_overall + stream.randint(-10, 5)
            position_bonus = int((weight - 1.0) * 12)
            attributes[attribute] = max(1, min(100, base + position_bonus))

        return cls._normalize_generated_attributes(
            position=position, attributes=attributes, target_overall=target_overall,
        )

    @staticmethod
    def _validate_tier(tier: PlayerTier) -> None:
        if tier not in PlayerTier.values:
            raise InvalidPlayerTierError(f"Invalid player tier: {tier}")

    @staticmethod
    def _validate_position(position: Position) -> None:
        if position not in Position.values:
            raise InvalidPlayerPositionError(
                f"Invalid player position: {position}"
            )

    @classmethod
    def _generate_attributes(
        cls,
        *,
        position: Position,
        target_overall: int,
    ) -> dict[str, int]:
        weights = POSITION_WEIGHTS.get(position, {})
        primary_attributes = POSITION_PRIMARY_ATTRIBUTES.get(position, ())

        attributes: dict[str, int] = {}

        for attribute in ALL_ATTRIBUTES:
            weight = weights.get(attribute, 1.0)

            if attribute in primary_attributes:
                base = target_overall + random.randint(0, 12)
            else:
                base = target_overall + random.randint(-12, 6)

            position_bonus = int((weight - 1.0) * 15)
            value = base + position_bonus

            attributes[attribute] = max(1, min(100, value))

        return attributes

    @classmethod
    def _normalize_generated_attributes(cls, *, position, attributes, target_overall):
        """Adjust the lowest/highest ratings without erasing position strengths.

        Each bounded unit step preserves the primary/secondary skill ordering
        and checks the actual weighted OVR against the selected target.
        """
        fields = list(ALL_ATTRIBUTES)
        primary = set(POSITION_PRIMARY_ATTRIBUTES.get(position, ()))
        secondary = set(fields) - primary
        # Preserve football specialization throughout normalization, including
        # externally generated academy profiles. Never repeatedly drain the
        # highest-weight attribute merely because it changes OVR fastest.
        floor = max((attributes[f] for f in secondary), default=1)
        for field in primary:
            attributes[field] = max(attributes[field], floor)
        for _ in range(20000):
            current = cls._calculate_overall(position=position, attributes=attributes)
            if current == target_overall:
                return attributes
            direction = 1 if current < target_overall else -1
            primary_floor = min((attributes[f] for f in primary), default=100)
            secondary_ceiling = max((attributes[f] for f in secondary), default=1)
            candidates = [f for f in fields if 1 <= attributes[f] + direction <= 100
                          and not (direction < 0 and f in primary and attributes[f] <= secondary_ceiling)
                          and not (direction > 0 and f in secondary and attributes[f] >= primary_floor)]
            if not candidates:
                break
            chosen = max(candidates, key=lambda f: direction * (target_overall - attributes[f]))
            attributes[chosen] += direction
            fields.append(fields.pop(0))
        raise RuntimeError("Unable to normalize generated rating.")

    @classmethod
    def _calculate_overall(
        cls,
        *,
        position: Position,
        attributes: dict[str, int],
    ) -> int:
        weights = POSITION_WEIGHTS.get(position, {})

        weighted_total = Decimal("0")
        total_weight = Decimal("0")

        for attribute in ALL_ATTRIBUTES:
            weight = Decimal(str(weights.get(attribute, 1.0)))
            weighted_total += attributes[attribute] * weight
            total_weight += weight

        if total_weight == 0:
            return 1

        overall = int((weighted_total / total_weight).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
        return max(1, min(100, overall))

    @staticmethod
    def _safe_anniversary(*, today: date, years_ago: int) -> date:
        """Return the same month/day years ago, clamping Feb 29 when needed."""
        target_year = today.year - years_ago
        target_day = min(
            today.day,
            calendar.monthrange(target_year, today.month)[1],
        )
        return date(target_year, today.month, target_day)

    @classmethod
    def _generate_birth_date(cls, age: int) -> date:
        if not cls.MIN_AGE <= age <= cls.MAX_AGE:
            raise ValueError(
                f"Age must be between {cls.MIN_AGE} and {cls.MAX_AGE}."
            )

        today = timezone.localdate()

        latest_birth_date = cls._safe_anniversary(
            today=today,
            years_ago=age,
        )
        previous_anniversary = cls._safe_anniversary(
            today=today,
            years_ago=age + 1,
        )
        earliest_birth_date = previous_anniversary + timedelta(days=1)

        days_between = (latest_birth_date - earliest_birth_date).days
        random_days = random.randint(0, days_between)

        return earliest_birth_date + timedelta(days=random_days)
