from decimal import Decimal, ROUND_HALF_UP
from typing import Any

CATEGORIES = ('supervisor', 'coordinator', 'technician', 'software_iii', 'software_ii', 'it_developer', 'software_developer', 'business_analyst', 'manufacturing_engineer')
MANAGEMENT = ('supervisor', 'coordinator')
SOFTWARE = ('software_iii', 'software_ii', 'it_developer', 'software_developer', 'business_analyst', 'manufacturing_engineer')
REGIONAL_ALIASES = {'supervisores': 'supervisor', 'coordinadores': 'coordinator', 'tecnicos': 'technician', 'técnicos': 'technician'}

def D(value: Any) -> Decimal:
    return Decimal(str(value))

def money(value: Decimal) -> float:
    return float(value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP))

def _count(p: dict, category: str) -> int:
    return int(p.get(f'{category}_count', p.get(category, 0)) or 0)

def _rate(p: dict, category: str) -> Decimal:
    return D(p.get(f'{category}_rate', p.get('rates', {}).get(category, 0)) or 0)

def _region_counts(region: dict) -> dict:
    counts = {c: 0 for c in CATEGORIES}
    for key, value in region.items():
        category = REGIONAL_ALIASES.get(key, key)
        if category in counts and key not in ('supervisor_hours_per_week', 'supervisor_hours'):
            counts[category] = int(value or 0)
    return counts

def weekly_fee_base(p: dict, counts: dict | None = None) -> Decimal:
    counts = counts or {c: _count(p, c) for c in CATEGORIES}
    return D(p.get('hours_per_week', 40)) * sum((_rate(p, c) * counts.get(c, 0) for c in CATEGORIES), Decimal('0'))

def regional_weekly_fee_base(p: dict) -> Decimal:
    total = Decimal('0')
    hours = D(p.get('hours_per_week', 40))
    for region in p.get('regional_data') or []:
        counts = _region_counts(region)
        supervisor_hours = region.get('supervisor_hours_per_week', region.get('supervisor_hours'))
        total += weekly_fee_base(p, counts) - _rate(p, 'supervisor') * counts['supervisor'] * hours
        total += _rate(p, 'supervisor') * counts['supervisor'] * D(supervisor_hours if supervisor_hours is not None else hours)
    return total

def regional_counts(p: dict) -> dict:
    counts = {c: 0 for c in CATEGORIES}
    hours = D(p.get('hours_per_week', 40))
    for region in p.get('regional_data') or []:
        region_counts = _region_counts(region)
        for category, value in region_counts.items():
            counts[category] += value
        supervisor_hours = region.get('supervisor_hours_per_week', region.get('supervisor_hours'))
        if supervisor_hours is not None and D(supervisor_hours) < hours:
            counts['supervisor'] -= region_counts['supervisor']
    return counts

def overtime_category(p: dict, categories: tuple[str, ...], hours: Decimal, counts: dict | None = None) -> Decimal:
    counts = counts or {c: _count(p, c) for c in CATEGORIES}
    count = sum(counts.get(c, 0) for c in categories)
    if not count:
        return Decimal('0')
    total = sum((_rate(p, c) * counts.get(c, 0) for c in categories), Decimal('0'))
    return hours * D(p.get('overtime_multiplier', 2)) * total / D(count)

def calculate_proposal(p: dict) -> dict:
    weeks = D(p.get('weeks_per_month', 52)) / D(12) if p.get('weeks_per_month') in (None, 0) else D(p.get('weeks_per_month'))
    months = D(p.get('months', 1))
    regional = bool(p.get('regional_data'))
    counts = regional_counts(p) if regional else {c: _count(p, c) for c in CATEGORIES}
    base_weekly = regional_weekly_fee_base(p) if regional else weekly_fee_base(p, counts)
    management_ot = overtime_category(p, MANAGEMENT, D(p.get('overtime_hours_management', p.get('overtime_hours_per_month', 0))), counts)
    technical_ot = overtime_category(p, ('technician',), D(p.get('overtime_hours_technical', 0)), counts)
    software_ot = overtime_category(p, SOFTWARE, D(p.get('overtime_hours_software', 0)), counts)
    weekly_ot = (management_ot + technical_ot + software_ot) / weeks
    weekly_total = base_weekly + weekly_ot
    return {'weekly_base': money(base_weekly), 'weekly_overtime': money(weekly_ot), 'weekly_total': money(weekly_total), 'monthly_equivalent': money(weekly_total * weeks), 'term_total': money(weekly_total * weeks * months), 'overtime': {'management': money(management_ot / weeks), 'technical': money(technical_ot / weeks), 'software': money(software_ot / weeks)}, 'weeks_per_month': float(weeks), 'currency': 'USD', 'regional': regional}
