#This service is used for build_einvoice_payload(invoice),generate_irn(invoice),get_irn_details(irn),cancel_irn(invoice, reason, remark)

import json
import requests
import re
from datetime import datetime
from decimal import Decimal, ROUND_HALF_UP
from flask import current_app
from sqlalchemy import func
from app import db
from app.models import EInvoiceAPILog, InvoiceItem, ProformaInvoiceItem, QuoteItem, StateMaster, CreditNoteItem


class MyGSTEInvoiceService:

    def __init__(self):
        self.base_url = (current_app.config.get("MYGST_API_BASE_URL") or "").rstrip("/")
        self.source = current_app.config.get("MYGST_SOURCE", "API")

        if not self.base_url:
            raise Exception("MYGST_API_BASE_URL is not configured.")

    def get_branch_credentials(self, seller_gstin):
        seller_gstin = (seller_gstin or "").strip().upper()

        delhi_gstin = (current_app.config.get("MYGST_DELHI_GSTIN") or "").strip().upper()
        bangalore_gstin = (current_app.config.get("MYGST_BANGALORE_GSTIN") or "").strip().upper()
        hyderabad_gstin = (current_app.config.get("MYGST_HYDERABAD_GSTIN") or "").strip().upper()

        if seller_gstin == delhi_gstin:
            return {
                "gstin": current_app.config.get("MYGST_DELHI_GSTIN"),
                "username": current_app.config.get("MYGST_DELHI_USERNAME"),
                "password": current_app.config.get("MYGST_DELHI_PASSWORD"),
                "customer_id": current_app.config.get("MYGST_DELHI_CUSTOMER_ID"),
                "api_id": current_app.config.get("MYGST_DELHI_API_ID"),
                "api_secret": current_app.config.get("MYGST_DELHI_API_SECRET"),
                "source": self.source,
            }

        if seller_gstin == bangalore_gstin:
            return {
                "gstin": current_app.config.get("MYGST_BANGALORE_GSTIN"),
                "username": current_app.config.get("MYGST_BANGALORE_USERNAME"),
                "password": current_app.config.get("MYGST_BANGALORE_PASSWORD"),
                "customer_id": current_app.config.get("MYGST_BANGALORE_CUSTOMER_ID"),
                "api_id": current_app.config.get("MYGST_BANGALORE_API_ID"),
                "api_secret": current_app.config.get("MYGST_BANGALORE_API_SECRET"),
                "source": self.source,
            }
        
        if seller_gstin == hyderabad_gstin:
            return {
                "gstin": current_app.config.get("MYGST_HYDERABAD_GSTIN"),
                "username": current_app.config.get("MYGST_HYDERABAD_USERNAME"),
                "password": current_app.config.get("MYGST_HYDERABAD_PASSWORD"),
                "customer_id": current_app.config.get("MYGST_HYDERABAD_CUSTOMER_ID"),
                "api_id": current_app.config.get("MYGST_HYDERABAD_API_ID"),
                "api_secret": current_app.config.get("MYGST_HYDERABAD_API_SECRET"),
                "source": self.source,
            }

        raise Exception(
            f"E-Invoice credentials are not configured for seller GSTIN: {seller_gstin}"
        )

    def headers(self, seller_gstin):
        creds = self.get_branch_credentials(seller_gstin)

        required_keys = [
            "gstin",
            "username",
            "password",
            "customer_id",
            "api_id",
            "api_secret",
            "source",
        ]

        missing = [key for key in required_keys if not creds.get(key)]
        if missing:
            raise Exception(
                "Missing E-Invoice API credential(s): " + ", ".join(missing)
            )

        return {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "GSTIN": creds["gstin"],
            "Username": creds["username"],
            "Password": creds["password"],
            "CustomerId": creds["customer_id"],
            "APIId": creds["api_id"],
            "APISecret": creds["api_secret"],
            "Source": creds["source"],
        }
    # -------------------------
    # GSTIN Validation
    # -------------------------
    def is_valid_gstin(self, gstin):

        if not gstin:
            return False

        gstin = gstin.strip().upper()

        # Normal GST registrations use ``Z`` as the 14th character.
        # GST TDS/TCS registrations use ``D`` / ``C`` respectively.
        # A TDS/TCS registration may be based on either PAN or TAN, so we
        # support both structures instead of rejecting a valid government
        # Tax Deductor GSTIN before the request is even sent to the IRP.
        pan_based_pattern = (
            r"^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z][A-Z0-9][ZDC][A-Z0-9]$"
        )
        tan_based_tds_tcs_pattern = (
            r"^[0-9]{2}[A-Z]{4}[0-9]{5}[A-Z][A-Z0-9][DC][A-Z0-9]$"
        )

        return bool(
            re.match(pan_based_pattern, gstin)
            or re.match(tan_based_tds_tcs_pattern, gstin)
        )

    # -------------------------
    # API Logger
    # -------------------------
    def log_api(
        self,
        invoice_id,
        request_type,
        request_payload,
        response_payload,
        status,
        error_message=None
    ):

        log = EInvoiceAPILog(
            invoice_id=invoice_id,
            request_type=request_type,
            request_payload=json.dumps(request_payload, default=str),
            response_payload=json.dumps(response_payload, default=str),
            status=status,
            error_message=error_message
        )

        db.session.add(log)
        db.session.commit()

    # -------------------------
    # Build E-Invoice Payload
    # -------------------------
    def build_payload(self, invoice):

        quote = invoice.quote
        client = invoice.client
        branch = invoice.frozen_client_branch
        company_branch = invoice.company_branch

        if not quote:
            raise Exception("Quote missing in invoice")

        if not client:
            raise Exception("Client missing in invoice")

        if not branch:
            raise Exception("Client branch missing in invoice")

        if not company_branch:
            raise Exception("Company branch missing in invoice")

        if not invoice.invoice_date:
            raise Exception("Invoice date is missing")

        items = (
            invoice.items
            .order_by(InvoiceItem.sort_order.asc(), InvoiceItem.id.asc())
            .all()
        )

        # Backward-compatible fallback for an invoice created before the
        # invoice_items migration and not yet opened/snapshotted.
        if not items and invoice.pi:
            items = (
                invoice.pi.items
                .order_by(ProformaInvoiceItem.sort_order.asc(), ProformaInvoiceItem.id.asc())
                .all()
            )
        if not items:
            items = (
                quote.items
                .order_by(QuoteItem.sort_order.asc(), QuoteItem.id.asc())
                .all()
            )

        if not items:
            raise Exception("No invoice items found")

        seller_gstin = (company_branch.gst_no or "").strip().upper()
        buyer_gstin = (branch.gst or "").strip().upper()

        if not self.is_valid_gstin(seller_gstin):
            raise Exception(f"Invalid Seller GSTIN: {seller_gstin}")

        if buyer_gstin and not self.is_valid_gstin(buyer_gstin):
            raise Exception(f"Invalid Buyer GSTIN: {buyer_gstin}")

        seller_state_code = seller_gstin[:2]
        buyer_state_code = buyer_gstin[:2] if buyer_gstin else ("96" if self._is_foreign_buyer(branch) else "")

        if company_branch.state:
            seller_state = StateMaster.query.filter(
                func.lower(StateMaster.name) == company_branch.state.lower()
            ).first()
            if seller_state and seller_state.gst_state_code:
                seller_state_code = str(seller_state.gst_state_code).zfill(2)

        if branch.state and not self._is_foreign_buyer(branch):
            buyer_state = StateMaster.query.filter(
                func.lower(StateMaster.name) == branch.state.lower()
            ).first()
            if buyer_state and buyer_state.gst_state_code:
                buyer_state_code = str(buyer_state.gst_state_code).zfill(2)

        supply_type = "EXPWOP" if not buyer_gstin and self._is_foreign_buyer(branch) else self._get_buyer_supply_type(branch, invoice=invoice)

        item_list = []

        # Keep all tax calculations in Decimal. Using float accumulation can
        # introduce one-paise differences that are rejected by IRP.
        total_assessable = Decimal("0")
        total_cgst = Decimal("0")
        total_sgst = Decimal("0")
        total_igst = Decimal("0")
        total_invoice_value = Decimal("0")

        def _d(v):
            return Decimal(str(v or 0))

        def _r(v):
            return Decimal(str(v)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)

        invoice_subtotal = _d(invoice.subtotal)
        invoice_discount = _d(invoice.discount)
        invoice_taxable = invoice_subtotal - invoice_discount

        if invoice_taxable < 0:
            invoice_taxable = Decimal("0")

        invoice_cgst = _d(invoice.cgst)
        invoice_sgst = _d(invoice.sgst)
        invoice_igst = _d(invoice.igst)
        invoice_total = _d(invoice.total_amount)

        # The issued PI/invoice tax snapshot is the commercial source of truth.
        # IRN generation must never turn a zero-tax PI (notably SEZWOP) into an
        # 18% invoice merely because buyer/seller states differ.
        stored_tax_total = _r(invoice_cgst + invoice_sgst + invoice_igst)
        preserve_zero_tax = stored_tax_total == Decimal("0.00")

        if preserve_zero_tax and supply_type == "SEZWP":
            # A tax-free invoice for an SEZ customer is necessarily without
            # payment of tax. This also protects older branch masters recorded
            # simply as SEZ / SEZWP while the quote/PI explicitly carries zero tax.
            supply_type = "SEZWOP"

        total_item_gross = sum((_d(item.amount) for item in items), Decimal("0"))

        if total_item_gross <= 0:
            total_item_gross = sum(
                (_d(item.qty) * _d(item.rate) for item in items),
                Decimal("0")
            )

        allocated_discount = Decimal("0")
        item_count = len(items)

        for idx, item in enumerate(items, start=1):

            qty_dec = _d(item.qty)
            rate_dec = _d(item.rate)
            gross_dec = _d(item.amount)

            if qty_dec <= 0:
                qty_dec = Decimal("1")

            if gross_dec <= 0:
                gross_dec = qty_dec * rate_dec

            if invoice_discount > 0 and total_item_gross > 0:
                if idx == item_count:
                    # Reconcile the final line so total item discounts equal
                    # the exact document discount after paise rounding.
                    item_discount = _r(invoice_discount - allocated_discount)
                else:
                    item_discount = _r(
                        (gross_dec / total_item_gross) * invoice_discount
                    )
                    allocated_discount += item_discount
            else:
                item_discount = Decimal("0")

            taxable_dec = gross_dec - item_discount

            if taxable_dec < 0:
                taxable_dec = Decimal("0")

            # SEZWOP invoices may still carry the underlying GST rate in the
            # IRN item while the tax amount remains zero. For any other explicit
            # zero-tax PI/invoice, send GST rate 0 so payload and invoice agree.
            gst_rate = Decimal("18") if supply_type == "SEZWOP" else Decimal("18")
            if preserve_zero_tax and supply_type != "SEZWOP":
                gst_rate = Decimal("0")

            cgst_dec = Decimal("0")
            sgst_dec = Decimal("0")
            igst_dec = Decimal("0")

            if preserve_zero_tax:
                pass
            elif supply_type in ["SEZWP", "SEZWOP"]:
                igst_dec = (
                    _r(taxable_dec * gst_rate / Decimal("100"))
                    if supply_type == "SEZWP"
                    else Decimal("0")
                )
            elif seller_state_code == buyer_state_code:
                # IRP requires CGST and SGST to be exactly equal on every line.
                # Do not calculate total GST and then split it, because an odd
                # paisa produces values such as 1399.77 and 1399.76.
                half_rate = gst_rate / Decimal("2")
                cgst_dec = _r(taxable_dec * half_rate / Decimal("100"))
                sgst_dec = cgst_dec
            else:
                igst_dec = _r(taxable_dec * gst_rate / Decimal("100"))

            total_item_value = taxable_dec + cgst_dec + sgst_dec + igst_dec

            item_data = {
                "SlNo": str(idx),
                "PrdDesc": (item.item_name or item.description or "Service")[:300],
                "IsServc": "Y",
                "HsnCd": "9983",
                "Qty": float(_r(qty_dec)),
                "Unit": "NOS",
                "UnitPrice": float(_r(rate_dec)),
                "TotAmt": float(_r(gross_dec)),
                "Discount": float(_r(item_discount)),
                "AssAmt": float(_r(taxable_dec)),
                "GstRt": float(gst_rate),
                "IgstAmt": float(_r(igst_dec)),
                "CgstAmt": float(_r(cgst_dec)),
                "SgstAmt": float(_r(sgst_dec)),
                "TotItemVal": float(_r(total_item_value))
            }

            item_list.append(item_data)

            total_assessable += _r(taxable_dec)
            total_cgst += _r(cgst_dec)
            total_sgst += _r(sgst_dec)
            total_igst += _r(igst_dec)
            total_invoice_value += _r(total_item_value)

        # IRP header totals must equal the sum of ItemList values. The invoice
        # may contain tax values calculated at document level or with an older
        # state-comparison rule, so use the item totals as the source of truth.
        total_assessable = _r(total_assessable)
        total_cgst = _r(total_cgst)
        total_sgst = _r(total_sgst)
        total_igst = _r(total_igst)
        total_invoice_value = _r(total_invoice_value)
        total_tax = _r(total_cgst + total_sgst + total_igst)

        # Keep the stored invoice and its PDF consistent with the IRN payload.
        invoice.subtotal = _r(total_item_gross)
        invoice.discount = _r(invoice_discount)
        invoice.tax = total_tax
        invoice.cgst = total_cgst
        invoice.sgst = total_sgst
        invoice.igst = total_igst
        invoice.total_amount = total_invoice_value

        payload = {
            "Version": "1.1",
            "TranDtls": {
                "TaxSch": "GST",
                "SupTyp": supply_type,
                "RegRev": "N",
                "IgstOnIntra": "N"
            },
            "DocDtls": {
                "Typ": "INV",
                "No": self._safe_doc_no(invoice.invoice_no),
                "Dt": invoice.invoice_date.strftime("%d/%m/%Y")
            },
            "SellerDtls": {
                "Gstin": seller_gstin,
                "LglNm": ((company_branch.company.name if company_branch.company else "") or "Seller")[:100],
                "Addr1": (company_branch.branch_address or "")[:100],
                "Loc": (company_branch.branch_name or "")[:100],
                "Pin": self._safe_pin(
                    getattr(company_branch, "pin_code", None),
                    self._get_default_seller_pin(seller_state_code)
                ),
                "Stcd": seller_state_code
            },
            "BuyerDtls": {
                "Gstin": buyer_gstin or "URP",
                "LglNm": (client.company_name or "Buyer")[:100],
                "Pos": buyer_state_code,
                "Addr1": (branch.address or "")[:100],
                "Loc": (branch.city or branch.branch_location or "")[:100],
                "Pin": 999999 if self._is_foreign_buyer(branch) else self._safe_pin(branch.pin_code, 110019),
                "Stcd": buyer_state_code
            },
            "ItemList": item_list,
            "ValDtls": {
                "AssVal": float(total_assessable),
                "CgstVal": float(total_cgst),
                "SgstVal": float(total_sgst),
                "IgstVal": float(total_igst),
                "TotInvVal": float(total_invoice_value),

                # Discount has already been allocated to ItemList and deducted
                # while calculating each AssAmt. Sending it again here makes
                # IRP subtract the same discount twice and raises error 2189.
                "Discount": 0.0
            }
        }

        return payload

    def build_credit_note_payload(self, credit_note):
        """Build an IRP e-invoice payload for a generated GST credit note."""
        invoice = credit_note.invoice
        company_branch = credit_note.company_branch
        branch = credit_note.client_branch
        client = credit_note.client

        if not invoice:
            raise Exception("Original invoice is missing for this credit note.")
        if not company_branch:
            raise Exception("Billing company branch is missing.")
        if not branch:
            raise Exception("Client billing branch is missing.")
        if not client:
            raise Exception("Client is missing.")

        seller_gstin = (company_branch.gst_no or "").strip().upper()
        buyer_gstin = (branch.gst or "").strip().upper()

        if len(seller_gstin) != 15:
            raise Exception("Valid seller GSTIN is required for credit-note IRN generation.")
        if buyer_gstin and not self.is_valid_gstin(buyer_gstin):
            raise Exception("Invalid buyer GSTIN for credit-note IRN generation.")

        seller_state_code = seller_gstin[:2]
        buyer_state_code = buyer_gstin[:2] if buyer_gstin else ("96" if self._is_foreign_buyer(branch) else "")
        supply_type = "EXPWOP" if not buyer_gstin and self._is_foreign_buyer(branch) else self._get_buyer_supply_type(branch)

        def _d(value):
            return Decimal(str(value or 0))

        def _r(value):
            return Decimal(str(value)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)

        rows = (
            CreditNoteItem.query
            .filter_by(credit_note_id=credit_note.id)
            .order_by(CreditNoteItem.id.asc())
            .all()
        )
        if not rows:
            raise Exception("No credit-note items are available for IRN generation.")

        item_list = []
        total_assessable = Decimal("0")
        total_cgst = Decimal("0")
        total_sgst = Decimal("0")
        total_igst = Decimal("0")
        total_invoice_value = Decimal("0")

        for idx, item in enumerate(rows, start=1):
            taxable = _r(_d(item.amount))
            gst_rate = _d(item.gst_rate or 18)

            cgst = Decimal("0")
            sgst = Decimal("0")
            igst = Decimal("0")

            if supply_type in ["SEZWP", "SEZWOP"]:
                if supply_type == "SEZWP":
                    igst = _r(taxable * gst_rate / Decimal("100"))
            elif seller_state_code == buyer_state_code:
                cgst = _r(taxable * (gst_rate / Decimal("2")) / Decimal("100"))
                sgst = cgst
            else:
                igst = _r(taxable * gst_rate / Decimal("100"))

            total_value = _r(taxable + cgst + sgst + igst)

            item_list.append({
                "SlNo": str(idx),
                "PrdDesc": (item.description or "Credit Note Adjustment")[:300],
                "IsServc": "Y",
                "HsnCd": str(item.hsn_code or "9983")[:8],
                "Qty": 1.0,
                "Unit": "NOS",
                "UnitPrice": float(taxable),
                "TotAmt": float(taxable),
                "Discount": 0.0,
                "AssAmt": float(taxable),
                "GstRt": float(gst_rate),
                "IgstAmt": float(igst),
                "CgstAmt": float(cgst),
                "SgstAmt": float(sgst),
                "TotItemVal": float(total_value),
            })

            total_assessable += taxable
            total_cgst += cgst
            total_sgst += sgst
            total_igst += igst
            total_invoice_value += total_value

        total_assessable = _r(total_assessable)
        total_cgst = _r(total_cgst)
        total_sgst = _r(total_sgst)
        total_igst = _r(total_igst)
        total_invoice_value = _r(total_invoice_value)
        total_tax = _r(total_cgst + total_sgst + total_igst)

        # Keep the saved credit note consistent with the IRP line calculations.
        credit_note.subtotal = total_assessable
        credit_note.tax = total_tax
        credit_note.cgst = total_cgst
        credit_note.sgst = total_sgst
        credit_note.igst = total_igst
        credit_note.total_amount = total_invoice_value

        payload = {
            "Version": "1.1",
            "TranDtls": {
                "TaxSch": "GST",
                "SupTyp": supply_type,
                "RegRev": "N",
                "IgstOnIntra": "N",
            },
            "DocDtls": {
                "Typ": "CRN",
                "No": self._safe_doc_no(credit_note.credit_note_no),
                "Dt": credit_note.credit_note_date.strftime("%d/%m/%Y"),
            },
            "SellerDtls": {
                "Gstin": seller_gstin,
                "LglNm": ((company_branch.company.name if company_branch.company else "") or "Seller")[:100],
                "Addr1": (company_branch.branch_address or "")[:100],
                "Loc": (company_branch.branch_name or "")[:100],
                "Pin": self._safe_pin(
                    getattr(company_branch, "pin_code", None),
                    self._get_default_seller_pin(seller_state_code),
                ),
                "Stcd": seller_state_code,
            },
            "BuyerDtls": {
                "Gstin": buyer_gstin or "URP",
                "LglNm": (client.company_name or "Buyer")[:100],
                "Pos": buyer_state_code,
                "Addr1": (branch.address or "")[:100],
                "Loc": (branch.city or branch.branch_location or "")[:100],
                "Pin": 999999 if self._is_foreign_buyer(branch) else self._safe_pin(branch.pin_code, 110019),
                "Stcd": buyer_state_code,
            },
            "ItemList": item_list,
            "ValDtls": {
                "AssVal": float(total_assessable),
                "CgstVal": float(total_cgst),
                "SgstVal": float(total_sgst),
                "IgstVal": float(total_igst),
                "TotInvVal": float(total_invoice_value),
            },
            "RefDtls": {
                "InvRm": (credit_note.remarks or credit_note.reason or f"Credit Note against Invoice {invoice.invoice_no}")[:100],
                "PrecDocDtls": [{
                    "InvNo": self._safe_doc_no(invoice.invoice_no),
                    "InvDt": invoice.invoice_date.strftime("%d/%m/%Y"),
                }],
            },
        }

        return payload

    def generate_credit_note_irn(self, credit_note, payload):
        """Generate and save IRN details for a credit note."""
        if not credit_note.company_branch or not credit_note.company_branch.gst_no:
            raise Exception("Billing company branch GSTIN is missing.")

        endpoint = current_app.config.get("MYGST_GENERATE_IRN_ENDPOINT")
        if not endpoint:
            raise Exception("MYGST_GENERATE_IRN_ENDPOINT is not configured.")
        if not payload:
            raise Exception("Credit-note IRN payload is empty.")

        url = f"{self.base_url}{endpoint}"
        invoice_id = credit_note.invoice_id

        try:
            current_app.logger.error("CREDIT NOTE IRN REQUEST JSON START")
            current_app.logger.error(json.dumps(payload, indent=2, default=str))
            current_app.logger.error("CREDIT NOTE IRN REQUEST JSON END")

            response = requests.post(
                url,
                headers=self.headers(credit_note.company_branch.gst_no),
                json=payload,
                timeout=60,
            )

            try:
                data = response.json()
            except Exception:
                data = {
                    "raw_response": response.text,
                    "status_code": response.status_code,
                    "content_type": response.headers.get("Content-Type"),
                    "url": url,
                }

            current_app.logger.error("CREDIT NOTE IRN RESPONSE JSON START")
            current_app.logger.error(json.dumps(data, indent=2, default=str))
            current_app.logger.error("CREDIT NOTE IRN RESPONSE JSON END")

            normal_success = self._is_api_success(response, data)
            duplicate_result = self._extract_duplicate_irn_result(data)
            success = normal_success or duplicate_result is not None

            if success:
                result = (
                    self._extract_irn_result(data)
                    if normal_success
                    else duplicate_result
                )
                self._apply_irn_result(credit_note, result)

                if not credit_note.irn:
                    raise Exception(
                        "IRN API returned success but no IRN was present in the response."
                    )

                db.session.commit()

                self.log_api(
                    invoice_id,
                    "CREDIT_NOTE_GENERATE",
                    payload,
                    data,
                    "SUCCESS",
                    None,
                )

                return {
                    "success": True,
                    "duplicate": duplicate_result is not None,
                    "status_code": response.status_code,
                    "data": data,
                }

            credit_note.einvoice_status = "Failed"
            credit_note.einvoice_error = json.dumps(data, default=str)
            db.session.commit()

            self.log_api(
                invoice_id,
                "CREDIT_NOTE_GENERATE",
                payload,
                data,
                "FAILED",
                json.dumps(data, default=str),
            )

            return {
                "success": False,
                "status_code": response.status_code,
                "data": data,
            }

        except Exception as exc:
            db.session.rollback()

            try:
                credit_note.einvoice_status = "Failed"
                credit_note.einvoice_error = str(exc)
                db.session.commit()
            except Exception:
                db.session.rollback()

            try:
                self.log_api(
                    invoice_id,
                    "CREDIT_NOTE_GENERATE",
                    payload,
                    {},
                    "FAILED",
                    str(exc),
                )
            except Exception:
                current_app.logger.exception("Unable to save credit-note IRN API log")

            return {"success": False, "error": str(exc)}

    def _safe_pin(self, value, default_pin=110019):
        try:
            value = str(value or "").strip()
            return int(value) if value.isdigit() and len(value) == 6 else default_pin
        except Exception:
            return default_pin
        
    def _get_default_seller_pin(self, state_code):
        """
        Fallback PIN codes used only when the company branch does not have
        a valid six-digit PIN code.

        The actual GST-registered branch PIN should always be stored in
        company_branch.pin_code.
        """
        default_pins = {
            "07": 110019,  # Delhi
            "29": 560001,  # Karnataka
            "36": 500001,  # Telangana - replace with actual Hyderabad GST PIN
        }

        state_code = str(state_code or "").strip().zfill(2)

        return default_pins.get(state_code, 110019)

    def _safe_doc_no(self, value):
        value = str(value or "").strip()

        # IRP generally allows alphabets, numbers, slash and hyphen.
        value = re.sub(r"[^A-Za-z0-9/-]", "-", value)

        return value[:16]
    
    def _is_foreign_buyer(self, branch):
        """Only explicit non-Indian country values qualify for foreign PIN 999999."""
        country = str(getattr(branch, "country", "") or "").strip().lower()
        return bool(country and country not in ("india", "in", "ind", "bharat"))

    def _get_buyer_supply_type(self, branch, invoice=None):
        """Resolve IRP supply type from the client branch master.

        B2B    = regular registered buyer
        SEZWP  = SEZ buyer with payment of tax
        SEZWOP = SEZ buyer without payment of tax

        The UI stores short master codes (SEZWP/SEZWOP), while older records can
        contain descriptive labels. Both are accepted. For generic/legacy SEZ
        records, a zero-tax invoice/quote is treated as SEZWOP.
        """
        if not str(getattr(branch, "gst", "") or "").strip():
            return "B2C"

        registration_type = str(
            getattr(branch, "gst_registration_type", "") or ""
        ).strip().upper()
        compact = " ".join(registration_type.replace("_", " ").replace("-", " ").split())

        without_tax_values = {
            "SEZWOP",
            "SEZ WITHOUT PAYMENT",
            "SEZ WITHOUT PAYMENT OF TAX",
            "SEZ WITHOUT TAX",
            "SEZ W/O PAYMENT OF TAX",
        }
        with_tax_values = {
            "SEZWP",
            "SEZ WITH PAYMENT",
            "SEZ WITH PAYMENT OF TAX",
            "SEZ WITH TAX",
        }

        if compact in without_tax_values:
            return "SEZWOP"
        if compact in with_tax_values:
            return "SEZWP"

        invoice_has_zero_tax = False
        quote_gst_disabled = False
        if invoice is not None:
            try:
                tax_total = sum(
                    Decimal(str(getattr(invoice, name, 0) or 0))
                    for name in ("cgst", "sgst", "igst")
                )
                invoice_has_zero_tax = tax_total.quantize(Decimal("0.01")) == Decimal("0.00")
            except Exception:
                invoice_has_zero_tax = False
            quote = getattr(invoice, "quote", None)
            if quote is not None:
                quote_gst_disabled = not bool(getattr(quote, "is_gst_applicable", True))

        if compact == "SEZ":
            return "SEZWOP" if (invoice_has_zero_tax or quote_gst_disabled) else "SEZWP"

        fallback_text = " ".join([
            str(getattr(branch, "address", "") or ""),
            str(getattr(branch, "branch_location", "") or ""),
            str(getattr(branch, "city", "") or ""),
        ]).upper()

        if "SEZ" in fallback_text:
            return "SEZWOP" if (invoice_has_zero_tax or quote_gst_disabled) else "SEZWP"

        return "B2B"

    def _is_api_success(self, response, data):
        """Return True when the API response represents a normal IRN success."""
        if response.status_code != 200 or not isinstance(data, dict):
            return False

        status_value = data.get("status_cd")
        if status_value is None:
            status_value = data.get("Status")
        if status_value is None:
            status_value = data.get("status")

        return str(status_value).strip() in {"1", "SUCCESS", "Success", "success"}

    def _extract_irn_result(self, data):
        """Extract the IRP result dictionary from common MyGST/API wrappers."""
        if not isinstance(data, dict):
            return {}

        current = data
        wrapper_keys = (
            "response_data",
            "ResponseData",
            "data",
            "Data",
            "result",
            "Result",
            "Einvoice",
            "EInvoice",
        )

        # Unwrap several levels because different MyGST responses may wrap the
        # actual IRP object differently.
        for _ in range(6):
            if not isinstance(current, dict):
                return {}

            # Stop as soon as this object contains any known IRN fields.
            if any(
                key in current
                for key in (
                    "Irn",
                    "IRN",
                    "irn",
                    "AckNo",
                    "SignedInvoice",
                    "SignedQRCode",
                    "SignedQrCode",
                )
            ):
                return current

            next_value = None
            for key in wrapper_keys:
                value = current.get(key)
                if isinstance(value, dict):
                    next_value = value
                    break

            if next_value is None:
                break

            current = next_value

        return current if isinstance(current, dict) else {}

    def _extract_duplicate_irn_result(self, data):
        """
        Extract IRN details from IRP duplicate-IRN response (error 2150).

        A duplicate response means the document already has a valid IRN on IRP,
        usually because the original success response was not saved locally.
        """
        if not isinstance(data, dict):
            return None

        errors = data.get("Error") or data.get("error") or []
        if isinstance(errors, dict):
            errors = [errors]

        has_duplicate_error = False
        for error in errors:
            if not isinstance(error, dict):
                continue
            error_code = str(
                error.get("ErrorCode")
                or error.get("error_code")
                or error.get("code")
                or ""
            ).strip()
            error_message = str(
                error.get("ErrorMessage")
                or error.get("error_message")
                or error.get("message")
                or ""
            ).upper()

            if error_code == "2150" or "DUPLICATE IRN" in error_message:
                has_duplicate_error = True
                break

        info_details = (
            data.get("infodtls")
            or data.get("InfoDtls")
            or data.get("info_details")
            or []
        )
        if isinstance(info_details, dict):
            info_details = [info_details]

        for info in info_details:
            if not isinstance(info, dict):
                continue

            info_code = str(
                info.get("InfCd")
                or info.get("InfoCode")
                or info.get("code")
                or ""
            ).strip().upper()

            desc = info.get("Desc") or info.get("desc") or info.get("Data") or {}
            if not isinstance(desc, dict):
                continue

            irn = desc.get("Irn") or desc.get("IRN") or desc.get("irn")
            if (has_duplicate_error or info_code == "DUPIRN") and irn:
                return desc

        return None

    def _parse_ack_date(self, value):
        """Parse common MyGST/IRP acknowledgement date formats."""
        if not value:
            return None
        if isinstance(value, datetime):
            return value

        text = str(value).strip()
        if not text:
            return None

        normalized = text.replace("Z", "")
        try:
            return datetime.fromisoformat(normalized)
        except Exception:
            pass

        for fmt in (
            "%Y-%m-%d %H:%M:%S",
            "%Y-%m-%dT%H:%M:%S",
            "%d/%m/%Y %H:%M:%S",
            "%d/%m/%Y",
        ):
            try:
                return datetime.strptime(normalized, fmt)
            except Exception:
                continue

        return None

    def _apply_irn_result(self, document, result):
        """Save common IRN fields on an Invoice or CreditNote model instance."""
        if not isinstance(result, dict):
            result = {}

        returned_irn = (
            result.get("Irn")
            or result.get("IRN")
            or result.get("irn")
        )
        if returned_irn:
            document.irn = returned_irn

        returned_ack_no = (
            result.get("AckNo")
            or result.get("ack_no")
            or result.get("Ackno")
        )
        if returned_ack_no:
            document.ack_no = returned_ack_no

        signed_invoice = result.get("SignedInvoice") or result.get("signed_invoice")
        if signed_invoice:
            document.signed_invoice = signed_invoice

        signed_qr_code = (
            result.get("SignedQRCode")
            or result.get("SignedQrCode")
            or result.get("signed_qr_code")
        )
        if signed_qr_code:
            document.signed_qr_code = signed_qr_code

        ack_date_raw = (
            result.get("AckDt")
            or result.get("AckDate")
            or result.get("ack_date")
        )
        parsed_ack_date = self._parse_ack_date(ack_date_raw)
        if parsed_ack_date:
            document.ack_date = parsed_ack_date

        document.einvoice_status = "Generated"
        document.einvoice_generated_at = datetime.utcnow()
        document.einvoice_error = None

    def get_irn_details(self, document, irn=None):
        """Fetch the complete IRN record, including SignedQRCode.

        Duplicate-IRN responses contain only IRN/Ack details. This method calls
        the configured Get IRN Details endpoint to recover SignedInvoice and
        SignedQRCode and saves them on the supplied Invoice/CreditNote object.
        """
        if not document.company_branch or not document.company_branch.gst_no:
            raise Exception("Billing company branch GSTIN is missing.")

        irn = (irn or getattr(document, "irn", None) or "").strip()
        if not irn:
            raise Exception("IRN is missing; cannot fetch IRN details.")

        endpoint = (
            current_app.config.get("MYGST_GET_IRN_DETAILS_ENDPOINT")
            or current_app.config.get("MYGST_GET_IRN_ENDPOINT")
        )
        if not endpoint:
            raise Exception(
                "MYGST_GET_IRN_DETAILS_ENDPOINT is not configured."
            )

        # NIC/MyGST "Get E-Invoice by IRN" is a path-parameter API:
        #   GET /eicore/v1.03/Invoice/irn/{irn}
        # It does not accept the IRN as ?irn=<value>.
        endpoint = str(endpoint).rstrip("/")
        url = f"{self.base_url}{endpoint}/{irn}"

        request_method = str(
            current_app.config.get("MYGST_GET_IRN_DETAILS_METHOD", "GET")
        ).strip().upper()
        timeout = int(current_app.config.get("MYGST_API_TIMEOUT", 60) or 60)
        headers = self.headers(document.company_branch.gst_no)

        # Kept for API audit logs. The GET request itself uses the IRN in URL.
        request_payload = {
            "irn": irn,
            "url": url,
            "method": request_method,
        }

        try:
            if request_method == "POST":
                # POST support is retained only for a provider-specific override.
                response = requests.post(
                    url,
                    headers=headers,
                    json={"irn": irn},
                    timeout=timeout,
                )
            else:
                response = requests.get(
                    url,
                    headers=headers,
                    timeout=timeout,
                )

            try:
                data = response.json()
            except Exception:
                data = {
                    "raw_response": response.text,
                    "status_code": response.status_code,
                    "content_type": response.headers.get("Content-Type"),
                    "url": response.url,
                }

            current_app.logger.info(
                "GET IRN DETAILS RESPONSE: %s",
                json.dumps(data, default=str),
            )

            if not self._is_api_success(response, data):
                error_text = json.dumps(data, default=str)
                self.log_api(
                    getattr(document, "invoice_id", None) or document.id,
                    "GET_IRN_DETAILS",
                    request_payload,
                    data,
                    "FAILED",
                    error_text,
                )
                return {
                    "success": False,
                    "status_code": response.status_code,
                    "data": data,
                    "error": error_text,
                }

            result = self._extract_irn_result(data)
            self._apply_irn_result(document, result)

            if not getattr(document, "signed_qr_code", None):
                # Some gateways wrap the IRP object one level deeper.
                nested = None
                for key in ("result", "Result", "Einvoice", "EInvoice"):
                    value = result.get(key) if isinstance(result, dict) else None
                    if isinstance(value, dict):
                        nested = value
                        break
                if nested:
                    self._apply_irn_result(document, nested)
                    result = nested

            db.session.commit()

            self.log_api(
                getattr(document, "invoice_id", None) or document.id,
                "GET_IRN_DETAILS",
                request_payload,
                data,
                "SUCCESS",
                None,
            )

            signed_qr_available = bool(
                getattr(document, "signed_qr_code", None)
            )

            return {
                "success": signed_qr_available,
                "status_code": response.status_code,
                "data": data,
                "signed_qr_available": signed_qr_available,
                "error": (
                    None
                    if signed_qr_available
                    else "IRP response was successful but SignedQRCode was absent."
                ),
            }

        except Exception as exc:
            db.session.rollback()
            current_app.logger.exception("Unable to fetch IRN details")
            return {"success": False, "error": str(exc)}

    def recover_irn_details(self, document):
        """Recover signed IRN fields for a document already generated on IRP."""
        return self.get_irn_details(document, getattr(document, "irn", None))

    # -------------------------
    # Cancel IRN
    # -------------------------
    def cancel_irn(self, invoice, reason="2", remark="Data entry mistake"):
        """Cancel an active invoice IRN through IRP.

        IRP permits cancellation only within its allowed window and requires a
        cancellation reason + remark. We intentionally retain the original IRN,
        acknowledgement and signed QR fields on the local invoice for audit.
        """
        if not invoice or not getattr(invoice, "irn", None):
            raise Exception("IRN is missing; cannot cancel e-invoice.")

        if not invoice.company_branch or not invoice.company_branch.gst_no:
            raise Exception("Billing company branch GSTIN is missing.")

        endpoint = current_app.config.get("MYGST_CANCEL_IRN_ENDPOINT")
        if not endpoint:
            raise Exception("MYGST_CANCEL_IRN_ENDPOINT is not configured.")

        reason = str(reason or "2").strip()
        remark = str(remark or "Data entry mistake").strip()[:100]
        payload = {
            "Irn": invoice.irn,
            "CnlRsn": reason,
            "CnlRem": remark,
        }
        url = f"{self.base_url}{endpoint}"

        try:
            response = requests.post(
                url,
                headers=self.headers(invoice.company_branch.gst_no),
                json=payload,
                timeout=60,
            )

            try:
                data = response.json()
            except Exception:
                data = {
                    "raw_response": response.text,
                    "status_code": response.status_code,
                    "content_type": response.headers.get("Content-Type"),
                    "url": url,
                }

            success = self._is_api_success(response, data)

            if success:
                invoice.einvoice_status = "Cancelled"
                invoice.einvoice_error = None
                db.session.commit()
                self.log_api(invoice.id, "CANCEL", payload, data, "SUCCESS", None)
                return {
                    "success": True,
                    "status_code": response.status_code,
                    "data": data,
                }

            error_text = json.dumps(data, default=str)
            self.log_api(invoice.id, "CANCEL", payload, data, "FAILED", error_text)
            return {
                "success": False,
                "status_code": response.status_code,
                "data": data,
                "error": error_text,
            }

        except Exception as exc:
            db.session.rollback()
            try:
                self.log_api(invoice.id, "CANCEL", payload, {}, "FAILED", str(exc))
            except Exception:
                current_app.logger.exception("Unable to save IRN cancellation API log")
            return {"success": False, "error": str(exc)}

    # -------------------------
    # Generate IRN
    # -------------------------
    def generate_irn(self, invoice, payload):

        if not invoice.company_branch or not invoice.company_branch.gst_no:
            raise Exception("Billing company branch GSTIN is missing.")

        endpoint = current_app.config.get("MYGST_GENERATE_IRN_ENDPOINT")
        if not endpoint:
            raise Exception("MYGST_GENERATE_IRN_ENDPOINT is not configured.")

        url = f"{self.base_url}{endpoint}"

        if not payload:
            raise Exception("IRN payload is empty. build_payload() did not return payload.")

        try:
            current_app.logger.error("IRN REQUEST JSON START")
            current_app.logger.error(json.dumps(payload, indent=2, default=str))
            current_app.logger.error("IRN REQUEST JSON END")

            response = requests.post(
                url,
                headers=self.headers(invoice.company_branch.gst_no),
                json=payload,
                timeout=60,
            )

            try:
                data = response.json()
            except Exception:
                data = {
                    "raw_response": response.text,
                    "status_code": response.status_code,
                    "content_type": response.headers.get("Content-Type"),
                    "url": url,
                }

            current_app.logger.error("IRN RESPONSE JSON START")
            current_app.logger.error(json.dumps(data, indent=2, default=str))
            current_app.logger.error("IRN RESPONSE JSON END")

            normal_success = self._is_api_success(response, data)
            duplicate_result = self._extract_duplicate_irn_result(data)
            success = normal_success or duplicate_result is not None

            if success:
                result = (
                    self._extract_irn_result(data)
                    if normal_success
                    else duplicate_result
                )
                self._apply_irn_result(invoice, result)

                if not invoice.irn:
                    raise Exception(
                        "IRN API returned success but no IRN was present in the response."
                    )

                db.session.commit()

                # A duplicate-IRN response normally omits SignedQRCode. Recover
                # the full IRN record immediately so the invoice QR can render.
                if not getattr(invoice, "signed_qr_code", None):
                    recovery = self.get_irn_details(invoice, invoice.irn)
                    if not recovery.get("success"):
                        current_app.logger.warning(
                            "IRN saved, but signed QR recovery failed for invoice %s: %s",
                            invoice.id,
                            recovery.get("error") or recovery.get("data"),
                        )

                self.log_api(
                    invoice.id,
                    "GENERATE",
                    payload,
                    data,
                    "SUCCESS",
                    None,
                )

                return {
                    "success": True,
                    "duplicate": duplicate_result is not None,
                    "status_code": response.status_code,
                    "data": data,
                }

            invoice.einvoice_status = "Failed"
            invoice.einvoice_error = json.dumps(data, default=str)
            db.session.commit()

            self.log_api(
                invoice.id,
                "GENERATE",
                payload,
                data,
                "FAILED",
                json.dumps(data, default=str),
            )

            return {
                "success": False,
                "status_code": response.status_code,
                "data": data,
            }

        except Exception as exc:
            db.session.rollback()

            try:
                invoice.einvoice_status = "Failed"
                invoice.einvoice_error = str(exc)
                db.session.commit()
            except Exception:
                db.session.rollback()

            try:
                self.log_api(
                    invoice.id,
                    "GENERATE",
                    payload,
                    {},
                    "FAILED",
                    str(exc),
                )
            except Exception:
                current_app.logger.exception("Unable to save IRN API log")

            return {
                "success": False,
                "error": str(exc),
            }

