"""
Service Déclaration TVA – 3310-CA3 Régime mini-réel (trimestriel)
Calcule automatiquement chaque case du CERFA à partir des écritures validées.

Cases CERFA 3310-CA3 identifiées sur le formulaire AAZ Marketing :
Section A – Montant des opérations réalisées
  A1  : Ventes, prestations de services (HT) → recettes 706xxx
  A2  : Autres opérations imposables (HT)
  A3  : Acquisitions intracommunautaires (HT)

Section B – Décompte de la TVA à payer
TVA BRUTE :
  08  : Opérations imposables taux 20% → base HT + TVA 20%
  09  : Opérations imposables taux 5,5% → base HT + TVA 5,5%
  9B  : Opérations imposables taux 10% → base HT + TVA 10%
  (17 : Total TVA brute = 08+09+9B)

TVA DÉDUCTIBLE :
  19  : Dont TVA sur immobilisations
  20  : Dont TVA sur autres biens et services
  (23 : Total TVA déductible)

RÉSULTAT :
  24  : TVA nette due (ligne 16 – ligne 23)
  25  : Crédit de TVA (si TVA déductible > TVA brute)
"""

from datetime import date, datetime
from decimal import Decimal, ROUND_HALF_UP
from typing import Optional

from sqlalchemy import func, extract

from app import db
from app.models import JournalEntry, EntryStatus


class TVADeclarationService:
    """
    Calcule les cases de la déclaration 3310-CA3 (mini-réel, trimestriel)
    pour une période donnée.
    """

    def __init__(self, period_start: date, period_end: date):
        self.period_start = period_start
        self.period_end   = period_end

    def compute(self) -> dict:
        """
        Retourne un dict avec toutes les cases CERFA calculées + détails.
        """
        # ── TVA collectée par taux ─────────────────────────────────────────────
        tva_20_base, tva_20_tva = self._tva_collected("20")
        tva_10_base, tva_10_tva = self._tva_collected("10")
        tva_55_base, tva_55_tva = self._tva_collected("5.5")

        total_tva_brute = tva_20_tva + tva_10_tva + tva_55_tva

        # ── TVA déductible ─────────────────────────────────────────────────────
        tva_deduc_immo    = self._tva_deductible_immo()
        tva_deduc_services = self._tva_deductible_services()
        total_tva_deductible = tva_deduc_immo + tva_deduc_services

        # ── Opérations réalisées (Section A) ──────────────────────────────────
        recettes_ht = self._recettes_ht()
        autres_ops  = Decimal("0")  # À compléter si acquisitions IC

        # ── Résultat ──────────────────────────────────────────────────────────
        tva_nette = total_tva_brute - total_tva_deductible
        tva_due   = tva_nette if tva_nette > 0 else Decimal("0")
        credit    = abs(tva_nette) if tva_nette < 0 else Decimal("0")

        # ── Détail par mois pour le rapport ───────────────────────────────────
        monthly_detail = self._monthly_detail()

        return {
            # Période
            "period_start": self.period_start,
            "period_end":   self.period_end,
            "quarter":      self._quarter_label(),

            # Section A – Opérations
            "A1_recettes_ht":      self._fmt(recettes_ht),
            "A2_autres_ops":       self._fmt(autres_ops),

            # Section B – TVA brute
            "ligne_08_base_20":    self._fmt(tva_20_base),
            "ligne_08_tva_20":     self._fmt(tva_20_tva),
            "ligne_09_base_55":    self._fmt(tva_55_base),
            "ligne_09_tva_55":     self._fmt(tva_55_tva),
            "ligne_9B_base_10":    self._fmt(tva_10_base),
            "ligne_9B_tva_10":     self._fmt(tva_10_tva),
            "ligne_17_total_brute": self._fmt(total_tva_brute),

            # Section B – TVA déductible
            "ligne_19_tva_immo":      self._fmt(tva_deduc_immo),
            "ligne_20_tva_services":  self._fmt(tva_deduc_services),
            "ligne_23_total_deduc":   self._fmt(total_tva_deductible),

            # Résultat
            "ligne_24_tva_due":    self._fmt(tva_due),
            "ligne_25_credit":     self._fmt(credit),

            # Indicateurs
            "solde": float(tva_nette),
            "is_credit": tva_nette < 0,

            # Détail mensuel pour graphique
            "monthly_detail": monthly_detail,

            # Récapitulatif détaillé par compte
            "detail_collectee":  self._detail_collectee(),
            "detail_deductible": self._detail_deductible(),

            # Avertissements
            "warnings": self._warnings(tva_20_base, tva_10_base, tva_55_base),
        }

    # ── Collectée ──────────────────────────────────────────────────────────────
    def _tva_collected(self, rate: str) -> tuple[Decimal, Decimal]:
        """Retourne (base_ht, tva) pour un taux donné."""
        # TVA collectée = compte 445710 avec tva_rate correspondant
        # Base HT = compte 706xxx associé
        rows = self._base_q().filter(
            JournalEntry.account_number.like("706%"),
            JournalEntry.tva_rate == rate,
        ).with_entities(
            func.sum(JournalEntry.amount_ht),
            func.sum(JournalEntry.tva_amount),
        ).first()
        ht  = Decimal(str(rows[0] or 0))
        tva = Decimal(str(rows[1] or 0))

        # Fallback : recalculer depuis les lignes 445710
        if tva == 0:
            tva_row = self._base_q().filter(
                JournalEntry.account_number == "445710",
                JournalEntry.tva_rate == rate,
            ).with_entities(func.sum(JournalEntry.credit)).first()
            tva = Decimal(str(tva_row[0] or 0))
            if tva > 0:
                r = {"20": Decimal("0.20"), "10": Decimal("0.10"), "5.5": Decimal("0.055")}.get(rate, Decimal("0.20"))
                ht = (tva / r).quantize(Decimal("0.01"), ROUND_HALF_UP)

        return ht.quantize(Decimal("0.01")), tva.quantize(Decimal("0.01"))

    def _recettes_ht(self) -> Decimal:
        row = self._base_q().filter(
            JournalEntry.account_number.like("706%"),
        ).with_entities(func.sum(JournalEntry.credit)).first()
        # Si credit nul, essayer amount_ht
        val = Decimal(str(row[0] or 0))
        if val == 0:
            row2 = self._base_q().filter(
                JournalEntry.account_number.like("706%"),
            ).with_entities(func.sum(JournalEntry.amount_ht)).first()
            val = Decimal(str(row2[0] or 0))
        return val.quantize(Decimal("0.01"))

    # ── Déductible ─────────────────────────────────────────────────────────────
    def _tva_deductible_immo(self) -> Decimal:
        """TVA déductible sur immobilisations (comptes 445620, 445610)."""
        row = self._base_q().filter(
            JournalEntry.account_number.in_(["445610", "445620"]),
        ).with_entities(func.sum(JournalEntry.debit)).first()
        return Decimal(str(row[0] or 0)).quantize(Decimal("0.01"))

    def _tva_deductible_services(self) -> Decimal:
        """TVA déductible sur biens et services courants (445560, 445561, 445660, 445566)."""
        row = self._base_q().filter(
            JournalEntry.account_number.in_(["445560", "445561", "445660", "445566"]),
        ).with_entities(func.sum(JournalEntry.debit)).first()
        return Decimal(str(row[0] or 0)).quantize(Decimal("0.01"))

    # ── Détails ────────────────────────────────────────────────────────────────
    def _detail_collectee(self) -> list:
        rows = self._base_q().filter(
            JournalEntry.account_number.like("706%"),
        ).with_entities(
            JournalEntry.tva_rate,
            func.count(JournalEntry.id),
            func.sum(JournalEntry.amount_ht),
            func.sum(JournalEntry.tva_amount),
        ).group_by(JournalEntry.tva_rate).all()
        return [{"rate": r[0], "count": r[1],
                 "base_ht": float(r[2] or 0), "tva": float(r[3] or 0)} for r in rows]

    def _detail_deductible(self) -> list:
        rows = self._base_q().filter(
            JournalEntry.account_number.in_(["445560","445561","445660","445566","445610","445620"]),
        ).with_entities(
            JournalEntry.account_number,
            JournalEntry.tva_rate,
            func.count(JournalEntry.id),
            func.sum(JournalEntry.debit),
        ).group_by(JournalEntry.account_number, JournalEntry.tva_rate).all()
        return [{"account": r[0], "rate": r[1], "count": r[2], "tva": float(r[3] or 0)} for r in rows]

    def _monthly_detail(self) -> list:
        rows = self._base_q().filter(
            JournalEntry.account_number.in_(["445560","445561","445660","445710"]),
        ).with_entities(
            extract("month", JournalEntry.entry_date).label("month"),
            JournalEntry.account_number,
            func.sum(JournalEntry.debit + JournalEntry.credit),
        ).group_by("month", JournalEntry.account_number).all()

        months = {}
        for row in rows:
            m = int(row[0])
            if m not in months:
                months[m] = {"collectee": 0, "deductible": 0}
            if row[1] == "445710":
                months[m]["collectee"] += float(row[2] or 0)
            else:
                months[m]["deductible"] += float(row[2] or 0)

        return [{"month": m, **v} for m, v in sorted(months.items())]

    def _warnings(self, base_20, base_10, base_55) -> list:
        warnings = []
        total_base = base_20 + base_10 + base_55
        recettes = self._recettes_ht()
        if total_base > 0 and recettes > 0:
            ratio = abs(float(total_base - recettes)) / float(recettes)
            if ratio > 0.1:
                warnings.append(
                    f"⚠️ Écart possible entre base imposable ({float(total_base):.2f} €) "
                    f"et recettes déclarées ({float(recettes):.2f} €). Vérifiez les écritures de ventes."
                )
        if total_base == 0 and recettes > 0:
            warnings.append("⚠️ Des recettes sont enregistrées mais aucune TVA collectée n'est détectée. Vérifiez les journaux de ventes.")
        return warnings

    # ── Helpers ────────────────────────────────────────────────────────────────
    def _base_q(self):
        return JournalEntry.query.filter(
            JournalEntry.entry_date >= self.period_start,
            JournalEntry.entry_date <= self.period_end,
            JournalEntry.status.in_([EntryStatus.VALIDATED, EntryStatus.EXPORTED]),
        )

    def _quarter_label(self) -> str:
        m = self.period_start.month
        q = (m - 1) // 3 + 1
        return f"T{q} {self.period_start.year}"

    @staticmethod
    def _fmt(val: Decimal) -> str:
        return f"{float(val):.2f}"

    @staticmethod
    def quarter_periods(year: int) -> list[dict]:
        """Retourne les 4 trimestres d'une année avec dates de dépôt."""
        from datetime import date
        return [
            {"label": f"T1 {year}", "start": date(year, 1, 1),  "end": date(year, 3, 31),  "deadline": date(year, 4, 19)},
            {"label": f"T2 {year}", "start": date(year, 4, 1),  "end": date(year, 6, 30),  "deadline": date(year, 7, 19)},
            {"label": f"T3 {year}", "start": date(year, 7, 1),  "end": date(year, 9, 30),  "deadline": date(year, 10, 19)},
            {"label": f"T4 {year}", "start": date(year, 10, 1), "end": date(year, 12, 31), "deadline": date(year, 1, 19)},
        ]
