from decimal import Decimal

from app.extensions import db
from app.models.accounting import AccountGroup, AccountLedger, Company, GSTSettlement, Voucher, VoucherEntry


def money(value):
    if value in [None, ""]:
        return Decimal("0.00")
    return Decimal(str(value)).quantize(Decimal("0.01"))


def clean_state(value):
    return (value or "").strip().lower()


class GSTService:
    def __init__(self, company_id):
        self.company_id = company_id
        self.company = Company.query.get(company_id)

    def is_intrastate(self, party_state):
        company_state = clean_state(getattr(self.company, "state", None))
        party_state = clean_state(party_state)

        # If state is missing, default to intrastate to avoid wrong IGST.
        # Later we can force state validation.
        if not company_state or not party_state:
            return True

        return company_state == party_state

    def calculate_line_gst(self, taxable_amount, gst_rate, party_state):
        taxable_amount = money(taxable_amount)
        gst_rate = money(gst_rate)

        total_tax = (taxable_amount * gst_rate / Decimal("100.00")).quantize(Decimal("0.01"))

        if self.is_intrastate(party_state):
            half = (total_tax / Decimal("2.00")).quantize(Decimal("0.01"))
            return {
                "cgst_amount": half,
                "sgst_amount": total_tax - half,
                "igst_amount": Decimal("0.00"),
                "total_tax": total_tax,
            }

        return {
            "cgst_amount": Decimal("0.00"),
            "sgst_amount": Decimal("0.00"),
            "igst_amount": total_tax,
            "total_tax": total_tax,
        }

    def get_or_create_group(self, group_name, nature):
        group = AccountGroup.query.filter_by(
            company_id=self.company_id,
            group_name=group_name,
            is_deleted=False,
        ).first()

        if group:
            return group

        group = AccountGroup(
            company_id=self.company_id,
            group_name=group_name,
            nature=nature,
            affects_gross_profit=False,
            sort_order=50,
        )
        db.session.add(group)
        db.session.flush()
        return group

    def get_or_create_tax_ledger(self, ledger_code, ledger_name, group_name, nature, opening_type):
        ledger = AccountLedger.query.filter_by(
            company_id=self.company_id,
            ledger_code=ledger_code,
            is_deleted=False,
        ).first()

        if ledger:
            return ledger

        group = self.get_or_create_group(group_name, nature)
        ledger = AccountLedger(
            company_id=self.company_id,
            ledger_code=ledger_code,
            ledger_name=ledger_name,
            group_id=group.id,
            ledger_type="tax",
            opening_balance=0,
            opening_balance_type=opening_type,
            gst_applicable=True,
        )
        db.session.add(ledger)
        db.session.flush()
        return ledger

    def output_cgst_ledger(self):
        return self.get_or_create_tax_ledger(
            "OUTPUT_CGST",
            "Output CGST",
            "Duties & Taxes",
            "liability",
            "cr",
        )

    def output_sgst_ledger(self):
        return self.get_or_create_tax_ledger(
            "OUTPUT_SGST",
            "Output SGST",
            "Duties & Taxes",
            "liability",
            "cr",
        )

    def output_igst_ledger(self):
        return self.get_or_create_tax_ledger(
            "OUTPUT_IGST",
            "Output IGST",
            "Duties & Taxes",
            "liability",
            "cr",
        )

    def input_cgst_ledger(self):
        return self.get_or_create_tax_ledger(
            "INPUT_CGST",
            "Input CGST",
            "Current Assets",
            "asset",
            "dr",
        )

    def input_sgst_ledger(self):
        return self.get_or_create_tax_ledger(
            "INPUT_SGST",
            "Input SGST",
            "Current Assets",
            "asset",
            "dr",
        )

    def input_igst_ledger(self):
        return self.get_or_create_tax_ledger(
            "INPUT_IGST",
            "Input IGST",
            "Current Assets",
            "asset",
            "dr",
        )

def dr_balance(debit, credit):
    return money(debit) - money(credit)


def cr_balance(debit, credit):
    return money(credit) - money(debit)


class GSTSettlementService:
    def __init__(self, company_id):
        self.company_id = company_id
        self.gst = GSTService(company_id)

    def ledger_balance_for_period(self, ledger_id, from_date, to_date):
        result = (
            db.session.query(
                db.func.coalesce(db.func.sum(VoucherEntry.debit_amount), 0).label("debit"),
                db.func.coalesce(db.func.sum(VoucherEntry.credit_amount), 0).label("credit"),
            )
            .join(Voucher, Voucher.id == VoucherEntry.voucher_id)
            .filter(
                Voucher.company_id == self.company_id,
                Voucher.status == "posted",
                Voucher.is_deleted.is_(False),
                Voucher.voucher_date >= from_date,
                Voucher.voucher_date <= to_date,
                VoucherEntry.ledger_id == ledger_id,
            )
            .one()
        )
        return money(result.debit), money(result.credit)

    def calculate(self, from_date, to_date):
        output_cgst_ledger = self.gst.output_cgst_ledger()
        output_sgst_ledger = self.gst.output_sgst_ledger()
        output_igst_ledger = self.gst.output_igst_ledger()
        input_cgst_ledger = self.gst.input_cgst_ledger()
        input_sgst_ledger = self.gst.input_sgst_ledger()
        input_igst_ledger = self.gst.input_igst_ledger()

        out_cgst_dr, out_cgst_cr = self.ledger_balance_for_period(output_cgst_ledger.id, from_date, to_date)
        out_sgst_dr, out_sgst_cr = self.ledger_balance_for_period(output_sgst_ledger.id, from_date, to_date)
        out_igst_dr, out_igst_cr = self.ledger_balance_for_period(output_igst_ledger.id, from_date, to_date)

        in_cgst_dr, in_cgst_cr = self.ledger_balance_for_period(input_cgst_ledger.id, from_date, to_date)
        in_sgst_dr, in_sgst_cr = self.ledger_balance_for_period(input_sgst_ledger.id, from_date, to_date)
        in_igst_dr, in_igst_cr = self.ledger_balance_for_period(input_igst_ledger.id, from_date, to_date)

        output_cgst = cr_balance(out_cgst_dr, out_cgst_cr)
        output_sgst = cr_balance(out_sgst_dr, out_sgst_cr)
        output_igst = cr_balance(out_igst_dr, out_igst_cr)

        input_cgst = dr_balance(in_cgst_dr, in_cgst_cr)
        input_sgst = dr_balance(in_sgst_dr, in_sgst_cr)
        input_igst = dr_balance(in_igst_dr, in_igst_cr)

        setoff_cgst = min(output_cgst, input_cgst)
        setoff_sgst = min(output_sgst, input_sgst)
        setoff_igst = min(output_igst, input_igst)

        net_cgst = output_cgst - input_cgst
        net_sgst = output_sgst - input_sgst
        net_igst = output_igst - input_igst
        net_total = net_cgst + net_sgst + net_igst

        return {
            "output_cgst": output_cgst,
            "output_sgst": output_sgst,
            "output_igst": output_igst,
            "input_cgst": input_cgst,
            "input_sgst": input_sgst,
            "input_igst": input_igst,
            "setoff_cgst": setoff_cgst,
            "setoff_sgst": setoff_sgst,
            "setoff_igst": setoff_igst,
            "net_cgst": net_cgst,
            "net_sgst": net_sgst,
            "net_igst": net_igst,
            "net_total": net_total,
            "status": "Payable" if net_total > 0 else "Receivable" if net_total < 0 else "Nil",
        }

    def create_or_update_settlement(self, from_date, to_date):
        calc = self.calculate(from_date, to_date)
        settlement = GSTSettlement.query.filter_by(
            company_id=self.company_id,
            from_date=from_date,
            to_date=to_date,
        ).first()

        if settlement and settlement.status in ["setoff_posted", "paid"]:
            return settlement, calc, False

        if not settlement:
            settlement = GSTSettlement(
                company_id=self.company_id,
                from_date=from_date,
                to_date=to_date,
            )
            db.session.add(settlement)

        for key, value in calc.items():
            if hasattr(settlement, key) and key != "status":
                setattr(settlement, key, value)

        settlement.status = "draft"
        db.session.flush()
        return settlement, calc, True