from __future__ import annotations

from datetime import datetime

import jdatetime

from blackout_notifier.models import TEHRAN, Outage

RTL = "\u200f"


def new_outage_message(bill_id: str, outage: Outage, now: datetime) -> str:
    return _join(
        "⚡ اطلاعیه خاموشی جدید",
        *_outage_lines(bill_id, outage),
        _sent_at(now),
    )


def updated_outage_message(bill_id: str, previous: Outage, current: Outage, now: datetime) -> str:
    labels = {
        "outage_date": "تاریخ",
        "start_time": "ساعت شروع",
        "stop_time": "ساعت پایان",
        "address": "محل",
        "reason": "دلیل",
        "is_planned": "وضعیت برنامه‌ریزی",
    }
    changes = []
    for field, label in labels.items():
        old_value = _display_value(getattr(previous, field))
        new_value = _display_value(getattr(current, field))
        if old_value != new_value:
            changes.append(f"✏️ {label}: {old_value} ← {new_value}")
    return _join(
        "🔄 تغییر در برنامه خاموشی",
        f"🆔 شناسه قبض: {bill_id}",
        f"🔖 شماره خاموشی: {current.outage_number}",
        *changes,
        _sent_at(now),
    )


def cancelled_outage_message(bill_id: str, outage: Outage, now: datetime) -> str:
    return _join(
        "✅ لغو احتمالی برنامه خاموشی",
        "این خاموشی در دو بررسی پیاپی مشاهده نشد.",
        *_outage_lines(bill_id, outage),
        _sent_at(now),
    )


def reactivated_outage_message(bill_id: str, outage: Outage, now: datetime) -> str:
    return _join(
        "⚠️ بازگشت برنامه خاموشی",
        *_outage_lines(bill_id, outage),
        _sent_at(now),
    )


def _outage_lines(bill_id: str, outage: Outage) -> tuple[str, ...]:
    return (
        f"🆔 شناسه قبض: {bill_id}",
        f"🔖 شماره خاموشی: {outage.outage_number}",
        f"📅 تاریخ: {outage.outage_date}",
        f"⏰ ساعت: {outage.start_time} تا {outage.stop_time}",
        f"📍 محل: {outage.address or 'نامشخص'}",
        f"📝 دلیل: {outage.reason or 'اعلام نشده'}",
    )


def _sent_at(now: datetime) -> str:
    local_now = now.astimezone(TEHRAN)
    jalali_now = jdatetime.datetime.fromgregorian(datetime=local_now.replace(tzinfo=None))
    return f"📥 ارسال در {jalali_now.strftime('%Y/%m/%d %H:%M:%S')}"


def _display_value(value: str | bool) -> str:
    if isinstance(value, bool):
        return "برنامه‌ریزی‌شده" if value else "برنامه‌ریزی‌نشده"
    return value or "نامشخص"


def _join(*lines: str) -> str:
    return f"{RTL}\n{RTL}".join(lines)
