"""Sof hisob-kitob funksiyalari (bazaga ham, Telegramga ham bog'liq emas).

Hamma joyda (bot xabarlari, Excel, PDF, Web Panel) pul va soat aynan shu
funksiyalar orqali hisoblanadi - natijalar bir-biridan farq qilmasligi uchun.
"""
import math
from datetime import datetime, timedelta

import config

MAX_SHIFT_HOURS = 16


def calculate_distance(lat1, lon1, lat2, lon2) -> float:
    R = 6371000
    phi1, phi2 = math.radians(lat1), math.radians(lat2)
    dphi = math.radians(lat2 - lat1)
    dlmb = math.radians(lon2 - lon1)
    a = math.sin(dphi / 2) ** 2 + math.cos(phi1) * math.cos(phi2) * math.sin(dlmb / 2) ** 2
    return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))


def _fmt(t: str) -> str:
    return "%H:%M:%S" if t.count(":") == 2 else "%H:%M"


def to_dt(date_str: str, t: str) -> datetime:
    return datetime.strptime(f"{date_str} {t}", f"%Y-%m-%d {_fmt(t)}")


def normalize_hhmm(raw) -> str:
    """'9:5' / '09:05' -> '09:05'. Noto'g'ri bo'lsa ValueError."""
    return datetime.strptime(str(raw).strip(), "%H:%M").strftime("%H:%M")


def minutes_between(start_hm: str, end_hm: str) -> int:
    s = datetime.strptime(start_hm, "%H:%M")
    e = datetime.strptime(end_hm, "%H:%M")
    return int((e - s).total_seconds() // 60)


# ================= KECHIKISH =================
def compute_lateness_minutes(date_str: str, actual_time: str, work_start: str, is_work_day: bool = True) -> int:
    """Kechikish daqiqasi. Dam olish kuni (kalendarda belgilanmagan kun yoki
    yakshanba) kelgan xodim uchun kechikish hisoblanmaydi."""
    if not is_work_day:
        return 0
    diff = int((to_dt(date_str, actual_time) - to_dt(date_str, work_start)).total_seconds() // 60)
    return max(0, diff)


# ================= ISH SOATLARI =================
def compute_paid_hours(date_str: str, check_in: str, check_out: str,
                       break_minutes: float, overtime_eligible: bool) -> float:
    """To'lanadigan soat. 2x huquqli xodim uchun 21:00'dan keyingi va
    yakshanba kunidagi soatlar 2 barobar (ko'pi bilan 2x)."""
    ci, co = to_dt(date_str, check_in), to_dt(date_str, check_out)
    if co < ci:
        co += timedelta(days=1)
    brk = max(0.0, break_minutes or 0.0) * 60
    total = max(0.0, (co - ci).total_seconds() - brk)
    if not overtime_eligible:
        return round(total / 3600, 2)
    if ci.weekday() == 6:
        return round(total / 3600 * 2, 2)
    cutoff = ci.replace(hour=21, minute=0, second=0)
    if co <= cutoff:
        return round(total / 3600, 2)
    if ci >= cutoff:
        return round(total / 3600 * 2, 2)
    normal = max(0.0, (cutoff - ci).total_seconds() - brk)
    rest_brk = max(0.0, brk - (cutoff - ci).total_seconds())
    over = max(0.0, (co - cutoff).total_seconds() - rest_brk)
    return round(normal / 3600 + over / 3600 * 2, 2)


def compute_work_and_paid_hours(date_str, check_in, check_out, break_minutes, overtime_eligible):
    ci, co = to_dt(date_str, check_in), to_dt(date_str, check_out)
    if co < ci:
        co += timedelta(days=1)
    brk = max(0.0, break_minutes or 0.0) * 60
    work = round(max(0.0, (co - ci).total_seconds() - brk) / 3600, 2)
    return work, compute_paid_hours(date_str, check_in, check_out, break_minutes, overtime_eligible)


# ================= SOATLIK STAVKA =================
def daily_norm_hours(work_start: str | None, work_end: str | None, override=None) -> float:
    """Bir kunlik ish soati normasi. Admin alohida kiritgan bo'lsa - o'shani,
    aks holda xodimning ish vaqtidan tushlikni ayirib hisoblaydi.
    09:00-18:00 (tushlik 60 daq.) => 8 soat."""
    if override and float(override) > 0:
        return float(override)
    try:
        mins = minutes_between(work_start or config.WORK_START_TIME, work_end or config.WORK_END_TIME)
    except (ValueError, TypeError):
        return 8.0
    if mins <= 0:
        return 8.0
    if mins > 6 * 60:  # 6 soatdan uzun smenada tushlik bor deb hisoblanadi
        mins -= config.LUNCH_MINUTES
    return round(max(1.0, mins / 60), 2)


def hourly_rate(monthly_salary, norm_days, daily_hours) -> float:
    norm_days = norm_days if norm_days and norm_days > 0 else 26
    daily_hours = daily_hours if daily_hours and daily_hours > 0 else 8
    return (monthly_salary or 0) / (norm_days * daily_hours)


# ================= VALIDATSIYA =================
def validate_schedule(start: str, end: str) -> str | None:
    """Xato matnini qaytaradi yoki None."""
    if minutes_between(start, end) <= 0:
        return "Ish tugash vaqti ish boshlanishidan keyin bo'lishi kerak"
    return None


def validate_shift(check_in: str | None, check_out: str | None) -> str | None:
    """Admin kiritgan kelish/ketish juftligini tekshiradi."""
    if not check_in or not check_out:
        return None
    ci = datetime.strptime(check_in[:5], "%H:%M")
    co = datetime.strptime(check_out[:5], "%H:%M")
    if co <= ci:
        return "Ketish vaqti kelish vaqtidan keyin bo'lishi kerak"
    if (co - ci) > timedelta(hours=MAX_SHIFT_HOURS):
        return f"Bir kunlik ish {MAX_SHIFT_HOURS} soatdan oshmasligi kerak"
    return None


def validate_admin_date(date_str: str, today: str) -> str | None:
    if date_str > today:
        return "Kelajakdagi sana uchun davomat kiritib bo'lmaydi"
    return None


# ================= JOYLASHUV =================
def evaluate_location(lat, lon, accuracy=None, forwarded=False, is_venue=False) -> dict:
    """Xodim yuborgan joylashuvni baholaydi.

    Qaytadi: {"ok": bool, "distance": int, "error": str|None, "flag": str|None}
      - forward qilingan yoki xaritadan "joy" (venue) tanlangan bo'lsa - rad etiladi.
      - aniqlik (horizontal_accuracy) yo'q yoki juda katta bo'lsa - qabul qilinadi,
        lekin "flag" bilan (adminga shubhali deb xabar beriladi). Xaritadan qo'lda
        tanlangan nuqtada odatda aniqlik ma'lumoti bo'lmaydi.
    """
    if forwarded:
        return {"ok": False, "distance": 0, "flag": None,
                "error": "Boshqa chatdan uzatilgan joylashuv qabul qilinmaydi. Pastdagi tugma orqali yuboring."}
    if is_venue:
        return {"ok": False, "distance": 0, "flag": None,
                "error": "Xaritadan tanlangan joy qabul qilinmaydi. Pastdagi «📍 Joylashuvni yuborish» tugmasini bosing."}
    distance = calculate_distance(config.OFFICE_LAT, config.OFFICE_LON, lat, lon)
    if distance > config.ALLOWED_RADIUS_METERS:
        return {"ok": False, "distance": int(distance), "flag": None,
                "error": f"Ofisgacha masofa: {int(distance)} metr. Ofis hududida bo'lishingiz kerak."}
    flag = None
    if accuracy is None:
        flag = "aniqlik_yoq"
    elif accuracy > config.LOCATION_MAX_ACCURACY_METERS:
        flag = f"aniqlik_{int(accuracy)}m"
    return {"ok": True, "distance": int(distance), "flag": flag, "error": None}
