from datetime import datetime
from decimal import Decimal, ROUND_HALF_UP

from app.models.accounting import (
    db,
    AccountLedger,
    FinancialYear,
    LedgerBalanceDaily,
    Voucher,
    VoucherEntry,
    VoucherType,
)


MONEY_QUANT = Decimal("0.01")


class PostingError(Exception):
    pass


def money(value):
    if value is None:
        value = 0
    return Decimal(str(value)).quantize(MONEY_QUANT, rounding=ROUND_HALF_UP)


class PostingEngine:
    """
    Central double-entry accounting posting engine.

    Use this service for every financial transaction:
    - manual vouchers
    - sales invoices
    - purchase invoices
    - receipts
    - payments
    - payroll summaries
    - stock valuation entries
    - imported ERP transactions
    """

    def __init__(self, company_id, user_id=None):
        self.company_id = company_id
        self.user_id = user_id

    def get_financial_year(self, voucher_date):
        fy = FinancialYear.query.filter(
            FinancialYear.company_id == self.company_id,
            FinancialYear.start_date <= voucher_date,
            FinancialYear.end_date >= voucher_date,
        ).first()

        if not fy:
            raise PostingError("No financial year found for this voucher date.")

        if fy.is_closed:
            raise PostingError("Financial year is closed. Posting is not allowed.")

        if fy.lock_date and voucher_date <= fy.lock_date:
            raise PostingError("This accounting period is locked. Posting is not allowed.")

        return fy

    def validate_ledger(self, ledger_id):
        ledger = AccountLedger.query.filter_by(
            id=ledger_id,
            company_id=self.company_id,
            active=True,
            is_deleted=False,
        ).first()

        if not ledger:
            raise PostingError(f"Invalid or inactive ledger: {ledger_id}")

        return ledger

    def get_voucher_type(self, voucher_type_id=None, type_code=None):
        query = VoucherType.query.filter_by(
            company_id=self.company_id,
            active=True,
            is_deleted=False,
        )

        if voucher_type_id:
            voucher_type = query.filter_by(id=voucher_type_id).first()
        elif type_code:
            voucher_type = query.filter_by(type_code=type_code).first()
        else:
            raise PostingError("Voucher type is required.")

        if not voucher_type:
            raise PostingError("Voucher type not found or inactive.")

        return voucher_type

    def generate_voucher_no(self, voucher_type):
        if voucher_type.numbering_method == "manual":
            raise PostingError("Manual voucher type requires voucher_no.")

        return voucher_type.next_number()

    def validate_entries(self, entries):
        if not entries or len(entries) < 2:
            raise PostingError("At least two voucher entries are required.")

        total_debit = Decimal("0.00")
        total_credit = Decimal("0.00")

        for index, entry in enumerate(entries, start=1):
            ledger_id = entry.get("ledger_id")
            debit = money(entry.get("debit_amount", 0))
            credit = money(entry.get("credit_amount", 0))

            if not ledger_id:
                raise PostingError(f"Ledger is missing in entry line {index}.")

            self.validate_ledger(ledger_id)

            if debit <= 0 and credit <= 0:
                raise PostingError(f"Either debit or credit amount is required in line {index}.")

            if debit > 0 and credit > 0:
                raise PostingError(f"Line {index} cannot have both debit and credit amount.")

            total_debit += debit
            total_credit += credit

        if total_debit != total_credit:
            raise PostingError(
                f"Voucher is not balanced. Debit: {total_debit}, Credit: {total_credit}"
            )

        return total_debit, total_credit

    def create_voucher(
        self,
        voucher_date,
        entries,
        voucher_type_id=None,
        type_code=None,
        voucher_no=None,
        branch_id=None,
        reference_no=None,
        narration=None,
        source_module=None,
        source_doc_type=None,
        source_doc_id=None,
        external_ref_no=None,
        auto_post=False,
        auto_approve=False,
    ):
        fy = self.get_financial_year(voucher_date)
        voucher_type = self.get_voucher_type(voucher_type_id=voucher_type_id, type_code=type_code)

        self.validate_entries(entries)

        if not voucher_no:
            voucher_no = self.generate_voucher_no(voucher_type)

        existing = Voucher.query.filter_by(
            company_id=self.company_id,
            financial_year_id=fy.id,
            voucher_no=voucher_no,
        ).first()

        if existing:
            raise PostingError(f"Voucher number already exists: {voucher_no}")

        if external_ref_no:
            duplicate_external = Voucher.query.filter_by(
                company_id=self.company_id,
                external_ref_no=external_ref_no,
                is_deleted=False,
            ).first()
            if duplicate_external:
                raise PostingError(f"External reference already posted: {external_ref_no}")

        status = "approved" if auto_approve else "draft"

        voucher = Voucher(
            company_id=self.company_id,
            branch_id=branch_id,
            financial_year_id=fy.id,
            voucher_type_id=voucher_type.id,
            voucher_no=voucher_no,
            voucher_date=voucher_date,
            reference_no=reference_no,
            narration=narration,
            source_module=source_module,
            source_doc_type=source_doc_type,
            source_doc_id=source_doc_id,
            external_ref_no=external_ref_no,
            status=status,
            created_by=self.user_id,
        )

        db.session.add(voucher)
        db.session.flush()

        for entry in entries:
            voucher_entry = VoucherEntry(
                voucher_id=voucher.id,
                ledger_id=entry.get("ledger_id"),
                cost_center_id=entry.get("cost_center_id"),
                branch_id=entry.get("branch_id") or branch_id,
                debit_amount=money(entry.get("debit_amount", 0)),
                credit_amount=money(entry.get("credit_amount", 0)),
                line_narration=entry.get("line_narration"),
                party_type=entry.get("party_type"),
                party_id=entry.get("party_id"),
                bill_ref_no=entry.get("bill_ref_no"),
                bill_ref_type=entry.get("bill_ref_type"),
            )
            db.session.add(voucher_entry)

        db.session.flush()

        if auto_post:
            if not auto_approve:
                voucher.status = "approved"
            self.post_voucher(voucher.id, commit=False)

        db.session.commit()
        return voucher

    def approve_voucher(self, voucher_id, approved_by=None, commit=True):
        voucher = self.get_voucher(voucher_id)

        if voucher.status != "draft":
            raise PostingError("Only draft vouchers can be approved.")

        if not voucher.is_balanced():
            raise PostingError("Voucher is not balanced.")

        voucher.status = "approved"
        voucher.approved_by = approved_by or self.user_id

        if commit:
            db.session.commit()

        return voucher

    def post_voucher(self, voucher_id, commit=True):
        voucher = self.get_voucher(voucher_id)

        if voucher.is_posted:
            raise PostingError("Voucher is already posted.")

        if voucher.status not in ["draft", "approved"]:
            raise PostingError("Only draft or approved vouchers can be posted.")

        self.get_financial_year(voucher.voucher_date)

        if not voucher.is_balanced():
            raise PostingError("Voucher is not balanced.")

        if len(voucher.entries) < 2:
            raise PostingError("Voucher must have at least two entries.")

        for entry in voucher.entries:
            self.validate_ledger(entry.ledger_id)

        voucher.status = "posted"
        voucher.is_posted = True
        voucher.posted_at = datetime.utcnow()

        self.rebuild_daily_balances_for_date(voucher.voucher_date)

        if commit:
            db.session.commit()

        return voucher

    def reverse_voucher(self, voucher_id, reversal_date, narration=None):
        original = self.get_voucher(voucher_id)

        if not original.is_posted:
            raise PostingError("Only posted vouchers can be reversed.")

        if original.status == "reversed":
            raise PostingError("Voucher is already reversed.")

        reversal_entries = []
        for entry in original.entries:
            reversal_entries.append(
                {
                    "ledger_id": entry.ledger_id,
                    "cost_center_id": entry.cost_center_id,
                    "branch_id": entry.branch_id,
                    "debit_amount": entry.credit_amount,
                    "credit_amount": entry.debit_amount,
                    "line_narration": f"Reversal of {original.voucher_no}",
                    "party_type": entry.party_type,
                    "party_id": entry.party_id,
                    "bill_ref_no": entry.bill_ref_no,
                    "bill_ref_type": entry.bill_ref_type,
                }
            )

        reversal = self.create_voucher(
            voucher_date=reversal_date,
            voucher_type_id=original.voucher_type_id,
            entries=reversal_entries,
            branch_id=original.branch_id,
            reference_no=f"REV-{original.voucher_no}",
            narration=narration or f"Reversal entry for voucher {original.voucher_no}",
            source_module="accounting",
            source_doc_type="voucher_reversal",
            source_doc_id=original.id,
            auto_approve=True,
            auto_post=True,
        )

        original.status = "reversed"
        db.session.commit()
        return reversal

    def cancel_draft_voucher(self, voucher_id):
        voucher = self.get_voucher(voucher_id)

        if voucher.is_posted:
            raise PostingError("Posted vouchers cannot be cancelled. Create reversal instead.")

        voucher.status = "cancelled"
        db.session.commit()
        return voucher

    def get_voucher(self, voucher_id):
        voucher = Voucher.query.filter_by(
            id=voucher_id,
            company_id=self.company_id,
            is_deleted=False,
        ).first()

        if not voucher:
            raise PostingError("Voucher not found.")

        return voucher

    def rebuild_daily_balances_for_date(self, balance_date):
        """
        Rebuilds debit/credit totals for all ledgers touched on a date.
        This keeps reporting fast while voucher_entry remains the source of truth.
        """
        posted_entries = (
            db.session.query(VoucherEntry)
            .join(Voucher, VoucherEntry.voucher_id == Voucher.id)
            .filter(
                Voucher.company_id == self.company_id,
                Voucher.voucher_date == balance_date,
                Voucher.is_posted.is_(True),
                Voucher.status == "posted",
                Voucher.is_deleted.is_(False),
            )
            .all()
        )

        ledger_totals = {}
        for entry in posted_entries:
            ledger_id = entry.ledger_id
            if ledger_id not in ledger_totals:
                ledger_totals[ledger_id] = {
                    "debit": Decimal("0.00"),
                    "credit": Decimal("0.00"),
                }
            ledger_totals[ledger_id]["debit"] += money(entry.debit_amount)
            ledger_totals[ledger_id]["credit"] += money(entry.credit_amount)

        for ledger_id, totals in ledger_totals.items():
            balance = LedgerBalanceDaily.query.filter_by(
                company_id=self.company_id,
                ledger_id=ledger_id,
                balance_date=balance_date,
            ).first()

            if not balance:
                balance = LedgerBalanceDaily(
                    company_id=self.company_id,
                    ledger_id=ledger_id,
                    balance_date=balance_date,
                )
                db.session.add(balance)

            balance.debit_total = totals["debit"]
            balance.credit_total = totals["credit"]

            net = totals["debit"] - totals["credit"]
            if net >= 0:
                balance.closing_balance = net
                balance.closing_type = "dr"
            else:
                balance.closing_balance = abs(net)
                balance.closing_type = "cr"

        db.session.flush()

    def post_manual_journal(self, voucher_date, debit_ledger_id, credit_ledger_id, amount, narration=None):
        amount = money(amount)
        entries = [
            {
                "ledger_id": debit_ledger_id,
                "debit_amount": amount,
                "credit_amount": 0,
                "line_narration": narration,
            },
            {
                "ledger_id": credit_ledger_id,
                "debit_amount": 0,
                "credit_amount": amount,
                "line_narration": narration,
            },
        ]

        return self.create_voucher(
            voucher_date=voucher_date,
            type_code="JV",
            entries=entries,
            narration=narration,
            source_module="accounting",
            source_doc_type="manual_journal",
            auto_approve=True,
            auto_post=True,
        )
