"""Strict match input validation shared by create and update operations."""
import math
import re
from datetime import date

HOME_ODDS_BY_SHEET = {1:2.00, 2:2.05, 3:2.10, 4:2.15, 5:2.20, 6:2.25, 7:2.30}

def text(value, label, limit=120, required=False):
    if not isinstance(value, str):
        raise ValueError(f'{label} must be text.')
    value = value.strip()
    if (required and not value) or len(value) > limit or re.search(r'[\x00-\x1f\x7f]', value):
        raise ValueError(f'Enter a valid {label.lower()} (maximum {limit} characters).')
    return value

def normalize_date(value):
    value = text(value, 'Match date', 10, True)
    iso = re.fullmatch(r'(\d{4})-(\d{2})-(\d{2})', value)
    uk = re.fullmatch(r'(\d{1,2})/(\d{1,2})/(\d{2}|\d{4})', value)
    try:
        if iso: year, month, day = map(int, iso.groups())
        elif uk:
            day, month, year = map(int, uk.groups())
            if len(uk[3]) == 2: year += 2000
        else: raise ValueError()
        if year < 1000: raise ValueError()
        return date(year, month, day).isoformat()
    except ValueError:
        raise ValueError('Enter a real match date in YYYY-MM-DD or DD/MM/YYYY format.') from None

def score_pair(value, label):
    value = text(value, label, 12)
    if not value: return '', None
    match = re.fullmatch(r'(\d{1,2})\s*[-:–]\s*(\d{1,2})', value)
    if not match or any(int(n) > 30 for n in match.groups()):
        raise ValueError(f'{label} must contain two whole numbers from 0 to 30.')
    pair = tuple(map(int, match.groups()))
    return f'{pair[0]} - {pair[1]}', pair

def validate_match(item):
    if not isinstance(item, dict): raise ValueError('Each match must be an object.')
    mid = text(item.get('id'), 'Match ID', 120, True)
    if not re.fullmatch(r'[A-Za-z0-9_-]+', mid): raise ValueError('Match ID contains invalid characters.')
    sheet = item.get('sheet')
    if isinstance(sheet, bool) or str(sheet) not in tuple(map(str, range(1,8))):
        raise ValueError('Source sheet must be a whole number from 1 to 7.')
    sheet = int(sheet)
    home = text(item.get('home'), 'Home team', required=True)
    away = text(item.get('away'), 'Away team', required=True)
    if ' '.join(home.casefold().split()) == ' '.join(away.casefold().split()):
        raise ValueError('Home and away teams must be different.')
    odds = {}
    for key in ('drawOdds', 'awayOdds'):
        value = item.get(key)
        try:
            if isinstance(value, bool): raise ValueError()
            value = float(value)
        except (TypeError, ValueError, OverflowError):
            raise ValueError('All odds must be numbers greater than 1 and no more than 1000.') from None
        if not math.isfinite(value) or not 1 < value <= 1000:
            raise ValueError('All odds must be finite numbers greater than 1 and no more than 1000.')
        odds[key] = value
    full, ft = score_pair(item.get('score', ''), 'Full-time score')
    half, ht = score_pair(item.get('halfTimeScore', ''), 'Half-time score')
    if ft and ht and any(h > f for h, f in zip(ht, ft)):
        raise ValueError('Half-time scores cannot exceed the corresponding full-time scores.')
    kickoff = text(item.get('kickoffTime', item.get('time', '')), 'Kick-off time', 5)
    if kickoff and not re.fullmatch(r'([01]\d|2[0-3]):[0-5]\d', kickoff):
        raise ValueError('Kick-off time must use HH:MM (00:00 to 23:59).')
    league = text(item.get('league', ''), 'League')
    prefix = league.split(',', 1)[0].strip() if ',' in league and league.split(',',1)[1].strip() else ''
    country = text(item.get('country', prefix), 'Country') or prefix
    if prefix and prefix.casefold() != country.casefold():
        raise ValueError('Country must match the country prefix in League.')
    return dict(id=mid, sheet=sheet, date=normalize_date(item.get('date')), home=home, away=away,
                homeOdds=HOME_ODDS_BY_SHEET[sheet], **odds, score=full, halfTimeScore=half,
                league=league, country=country, kickoffTime=kickoff)
