from datetime import date
from decimal import Decimal, ROUND_HALF_UP
from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import Sum

from apps.accounting.models import Account, LedgerEntry, Voucher
from apps.accounting.services import PostingService, VoucherService
from apps.audit.services import record_audit_event
from .models import Currency, ExchangeRate, FxRevaluationRun

DEFAULT_CURRENCIES = [
    ("NPR", "Nepalese Rupee", "रु", 1, 2),
    ("USD", "US Dollar", "$", 1, 2),
    ("EUR", "Euro", "€", 1, 2),
    ("INR", "Indian Rupee", "₹", 100, 2),
    ("GBP", "British Pound", "£", 1, 2),
    ("JPY", "Japanese Yen", "¥", 10, 0),
    ("CHF", "Swiss Franc", "CHF", 1, 2),
    ("AUD", "Australian Dollar", "A$", 1, 2),
]


def ensure_default_currencies(company) -> None:
    existing = {c.code: c for c in Currency.objects.filter(company=company)}
    for code, name, sym, unit, dec in DEFAULT_CURRENCIES:
        if code not in existing:
            Currency.objects.create(
                company=company,
                code=code,
                name=name,
                symbol=sym,
                unit=unit,
                decimal_places=dec,
                is_active=True,
            )
        elif existing[code].unit != unit:
            existing[code].unit = unit
            existing[code].save(update_fields=["unit"])


def get_effective_rate_details(company, from_currency: str, as_of_date: date, source: str | None = None) -> dict:
    if from_currency == company.base_currency:
        return {"unit": 1, "buy_rate": Decimal("1.000000"), "sell_rate": Decimal("1.000000"), "mid_rate": Decimal("1.000000"), "source": "BASE"}
    qs = ExchangeRate.objects.filter(
        company=company,
        from_currency=from_currency,
        to_currency=company.base_currency,
        effective_date__lte=as_of_date,
    )
    if source:
        qs = qs.filter(rate_source=source)
    rate_obj = qs.order_by("-effective_date", "-created_at").first()
    if not rate_obj:
        raise ValidationError(
            f"No exchange rate configured for {from_currency}/{company.base_currency} on or before {as_of_date}."
        )
    return {
        "unit": rate_obj.unit or 1,
        "buy_rate": rate_obj.buy_rate,
        "sell_rate": rate_obj.sell_rate,
        "mid_rate": rate_obj.mid_rate,
        "normalized_mid_rate": (rate_obj.mid_rate / Decimal(rate_obj.unit or 1)),
        "source": rate_obj.rate_source,
        "bank_name": rate_obj.bank_name,
        "effective_date": rate_obj.effective_date.isoformat(),
    }


def get_effective_rate(company, from_currency: str, as_of_date: date, source: str | None = None) -> Decimal:
    details = get_effective_rate_details(company, from_currency, as_of_date, source=source)
    return (details["mid_rate"] / Decimal(details["unit"] or 1)).quantize(Decimal("0.000001"))


def _get_or_create_fx_account(company, code: str, name: str, account_type: str) -> Account:
    acc, _ = Account.objects.get_or_create(
        company=company,
        code=code,
        defaults={
            "name": name,
            "account_type": account_type,
            "nfrs_mapping": "NAS 21",
            "is_group": False,
            "allow_direct_posting": True,
        },
    )
    return acc


@transaction.atomic
def run_period_end_revaluation(
    *,
    company,
    user,
    revaluation_date: date,
    currency_code: str,
    closing_rate: Decimal | None = None,
    scope: str = "ALL_MONETARY",
    auto_reverse_on: date | None = None,
) -> FxRevaluationRun:
    if not company.multi_currency_enabled:
        raise ValidationError("Multi-currency is disabled for this company.")
    if currency_code == company.base_currency:
        raise ValidationError("Cannot revalue base currency against itself.")

    cur = Currency.objects.filter(company=company, code=currency_code).first()
    unit = Decimal(cur.unit if cur and cur.unit else 1)
    if closing_rate is not None:
        normalized_rate = Decimal(str(closing_rate)) / unit
        display_rate = Decimal(str(closing_rate))
    else:
        details = get_effective_rate_details(company, currency_code, revaluation_date)
        display_rate = details["mid_rate"]
        normalized_rate = display_rate / Decimal(details["unit"] or 1)

    qs = LedgerEntry.objects.select_related("account").filter(
        company=company,
        transaction_currency=currency_code,
        posting_date__lte=revaluation_date,
        account__account_type__in=[Account.AccountType.ASSET, Account.AccountType.LIABILITY],
    )
    if scope == "BANK_ACCOUNTS":
        qs = qs.filter(account__control_role=Account.ControlRole.BANK)
    elif scope == "RECEIVABLES":
        qs = qs.filter(account__control_role=Account.ControlRole.SUNDRY_DEBTORS)
    elif scope == "PAYABLES":
        qs = qs.filter(account__control_role=Account.ControlRole.SUNDRY_CREDITORS)

    rows = qs.values("account_id").annotate(
        fc_d=Sum("debit"),
        fc_c=Sum("credit"),
        base_d=Sum("base_debit"),
        base_c=Sum("base_credit"),
    )

    q = Decimal("0.01")
    lines_data = []
    breakdown = []
    total_net_gain_loss = Decimal("0.00")

    for r in rows:
        acc = Account.objects.get(id=r["account_id"])
        fc_net = (r["fc_d"] or Decimal("0.00")) - (r["fc_c"] or Decimal("0.00"))
        book_base_net = (r["base_d"] or Decimal("0.00")) - (r["base_c"] or Decimal("0.00"))
        revalued_base = (fc_net * normalized_rate).quantize(q, rounding=ROUND_HALF_UP)
        diff = revalued_base - book_base_net
        if diff == Decimal("0.00"):
            continue
        total_net_gain_loss += diff
        breakdown.append(
            {
                "account_code": acc.code,
                "account_name": acc.name,
                "fc_net": str(fc_net),
                "book_base_net": str(book_base_net),
                "revalued_base": str(revalued_base),
                "unrealized_diff": str(diff),
            }
        )
        if diff > 0:
            lines_data.append({"account": acc, "debit": diff, "credit": Decimal("0.00"), "description": f"FX Reval {currency_code} @ {display_rate}"})
        else:
            lines_data.append({"account": acc, "debit": Decimal("0.00"), "credit": abs(diff), "description": f"FX Reval {currency_code} @ {display_rate}"})

    voucher = None
    reversal_voucher = None
    if lines_data and total_net_gain_loss != Decimal("0.00"):
        if total_net_gain_loss > 0:
            fx_gain = _get_or_create_fx_account(company, "4210", "Unrealized FX Gain", Account.AccountType.INCOME)
            lines_data.append({"account": fx_gain, "debit": Decimal("0.00"), "credit": total_net_gain_loss, "description": f"Unrealized FX Gain ({currency_code})"})
        else:
            fx_loss = _get_or_create_fx_account(company, "5210", "Unrealized FX Loss", Account.AccountType.EXPENSE)
            lines_data.append({"account": fx_loss, "debit": abs(total_net_gain_loss), "credit": Decimal("0.00"), "description": f"Unrealized FX Loss ({currency_code})"})

        voucher = VoucherService.create_draft(
            company=company,
            user=user,
            data={
                "voucher_type": Voucher.VoucherType.JOURNAL,
                "voucher_date": revaluation_date,
                "narration": f"Period-end FX Revaluation ({currency_code} @ {display_rate}/{unit})",
            },
            lines_data=lines_data,
        )
        voucher.status = Voucher.Status.APPROVED
        voucher.approved_by = user
        voucher.save(update_fields=["status", "approved_by"])
        voucher = PostingService.post_voucher(voucher=voucher, user=user)

        if auto_reverse_on and auto_reverse_on > revaluation_date:
            reversal_voucher = PostingService.reverse_voucher(
                voucher=voucher,
                user=user,
                reversal_date=auto_reverse_on,
                reason=f"Auto-reversal of unrealized FX revaluation ({currency_code})",
            )

    run = FxRevaluationRun.objects.create(
        company=company,
        revaluation_date=revaluation_date,
        currency_code=currency_code,
        scope=scope,
        closing_rate=display_rate,
        unrealized_gain_loss=total_net_gain_loss,
        breakdown=breakdown,
        auto_reverse_on=auto_reverse_on,
        voucher=voucher,
        reversal_voucher=reversal_voucher,
        created_by=user,
    )
    record_audit_event(
        company=company,
        actor=user,
        action="FX_REVALUATION_RUN",
        entity_type="FxRevaluationRun",
        entity_id=str(run.id),
        new_state={"currency": currency_code, "scope": scope, "rate": str(display_rate), "gain_loss": str(total_net_gain_loss)},
    )
    return run
