#!/usr/bin/env python3
"""Antigravity MCP App server for Maya OS Banking, Cash, Multi-Currency & Nepal Loans."""

from __future__ import annotations

import os
import sys
from datetime import date
from decimal import Decimal, ROUND_HALF_UP
from pathlib import Path

from mcp import types
from mcp.server.mcpserver import MCPServer

ROOT_DIR = Path(__file__).resolve().parent.parent
BACKEND_DIR = ROOT_DIR / "backend"
UI_DIST_HTML = Path(__file__).resolve().parent / "ui" / "dist" / "index.html"

if str(BACKEND_DIR) not in sys.path:
    sys.path.insert(0, str(BACKEND_DIR))

os.environ.setdefault("DB_ENGINE", "mysql")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")

import django  # noqa: E402

django.setup()

from django.db import close_old_connections  # noqa: E402
from django.db.models import Q  # noqa: E402
from django.utils import timezone  # noqa: E402

from apps.banking.models import BankAccount, BankStatementLine, CashAccount  # noqa: E402
from apps.banking.services import BankingService  # noqa: E402
from apps.currency.models import ExchangeRate  # noqa: E402
from apps.loans.calculators import generate_repayment_schedule  # noqa: E402
from apps.loans.models import BankFacility, BankGuarantee, DrawingPowerAssessment, NrbRegulatoryConfig  # noqa: E402
from apps.loans.services import LoanService  # noqa: E402
from apps.tenancy.models import Company  # noqa: E402

APP_URI = "ui://maya-treasury/app.html"

PANE_META = {
    "ui": {"resourceUri": APP_URI},
    "com.google.antigravity/ui": {
        "entrypoints": [
            {"type": "aux_pane", "title": "Maya Treasury"},
            {"type": "global", "title": "Maya Treasury"},
        ]
    },
}

APP_ONLY_META = {"ui": {"visibility": ["app"]}}

mcp = MCPServer("Maya Treasury Hub")


@mcp.resource(
    APP_URI,
    name="Maya Treasury App",
    title="Maya OS Treasury & Nepal Banking Hub",
    description="Single-file interactive React UI for Maya OS treasury exposure and Nepal Loan/OD/CC calculations.",
    mime_type="text/html;profile=mcp-app",
    meta={"ui": {"prefersBorder": False}},
)
def treasury_app_html() -> str:
    override_path = os.environ.get("MAYA_TREASURY_APP_HTML")
    html_path = Path(override_path) if override_path else UI_DIST_HTML
    if not html_path.exists():
        return (
            "<!doctype html><html><body><h2>Maya Treasury UI not built yet</h2>"
            "<p>Run <code>npm install &amp;&amp; npm run build</code> inside <code>mcp_app/ui</code>.</p>"
            "</body></html>"
        )
    return html_path.read_text(encoding="utf-8")


def _build_snapshot(company_code: str | None = None) -> dict:
    close_old_connections()
    try:
        companies = list(Company.objects.filter(is_active=True).order_by("code"))
        active = None
        if company_code:
            active = next((c for c in companies if c.code == company_code), None)
        if active is None and companies:
            active = companies[0]

        company_list = [
            {"code": c.code, "name": c.name, "base_currency": c.base_currency}
            for c in companies
        ]
        if active is None:
            return {
                "companies": [],
                "active_company": None,
                "summary": {
                    "total_bank_npr": "0.00",
                    "total_cash_npr": "0.00",
                    "total_loan_utilized_npr": "0.00",
                    "total_sanctioned_limit_npr": "0.00",
                    "total_bg_exposure_npr": "0.00",
                    "unreconciled_statement_lines": 0,
                    "nrb_threshold_pct": "25.00",
                },
                "banks": [],
                "cash_accounts": [],
                "fx_rates": [],
                "facilities": [],
                "guarantees": [],
            }

        bank_qs = (
            BankAccount.objects.select_related("bank_branch__bank", "gl_account")
            .filter(company=active, status=BankAccount.Status.ACTIVE)
            .order_by("account_name")
        )
        banks = []
        total_bank = Decimal("0.00")
        for ba in bank_qs:
            bal = BankingService.get_gl_balance(ba.gl_account)
            total_bank += bal
            banks.append(
                {
                    "id": str(ba.id),
                    "bank_name": ba.bank_branch.bank.name,
                    "branch_name": ba.bank_branch.name,
                    "account_name": ba.account_name,
                    "account_type": ba.account_type,
                    "masked_account_number": ba.account_number_masked,
                    "currency": ba.currency,
                    "ledger_balance": str(bal),
                }
            )

        cash_qs = (
            CashAccount.objects.select_related("gl_account", "custodian")
            .filter(company=active, is_active=True)
            .order_by("code")
        )
        cash_rows = []
        total_cash = Decimal("0.00")
        for ca in cash_qs:
            bal = BankingService.get_gl_balance(ca.gl_account)
            total_cash += bal
            cash_rows.append(
                {
                    "id": str(ca.id),
                    "code": ca.code,
                    "name": ca.name,
                    "cash_type": ca.cash_type,
                    "currency": ca.currency,
                    "custodian_name": (
                        ca.custodian.get_full_name() or ca.custodian.username
                        if ca.custodian
                        else ""
                    ),
                    "ledger_balance": str(bal),
                    "custody_limit": str(ca.imprest_limit),
                }
            )

        fx_qs = ExchangeRate.objects.filter(company=active).order_by("-effective_date", "from_currency")[:16]
        fx_rows = [
            {
                "currency": fx.from_currency,
                "rate_date": fx.effective_date.isoformat(),
                "source": fx.rate_source,
                "buy_rate": str(fx.buy_rate),
                "sell_rate": str(fx.sell_rate),
                "mid_rate": str(fx.mid_rate),
            }
            for fx in fx_qs
        ]

        fac_qs = (
            BankFacility.objects.select_related("bank_account__bank_branch__bank")
            .filter(company=active)
            .exclude(status=BankFacility.Status.CLOSED)
            .order_by("facility_code")
        )
        facilities = []
        total_loan_out = Decimal("0.00")
        total_sanctioned = Decimal("0.00")
        for fac in fac_qs:
            out = LoanService.get_outstanding_principal(fac)
            total_loan_out += out
            total_sanctioned += fac.sanctioned_limit
            dp_obj = (
                DrawingPowerAssessment.objects.filter(facility=fac)
                .order_by("-assessment_date")
                .first()
            )
            dp_val = dp_obj.effective_limit if dp_obj else fac.sanctioned_limit
            revolving_kind = (
                fac.facility_type
                if fac.facility_type in (BankFacility.FacilityType.OVERDRAFT, BankFacility.FacilityType.CASH_CREDIT)
                else "NONE"
            )
            facilities.append(
                {
                    "id": str(fac.id),
                    "facility_number": fac.facility_code,
                    "bank_name": fac.bank_account.bank_branch.bank.short_code,
                    "facility_type": fac.facility_type,
                    "revolving_kind": revolving_kind,
                    "currency": fac.currency,
                    "sanctioned_limit": str(fac.sanctioned_limit),
                    "utilized_principal": str(out),
                    "current_interest_rate": str(fac.effective_interest_rate),
                    "drawing_power": str(dp_val),
                    "status": fac.status,
                }
            )

        bg_qs = BankGuarantee.objects.filter(
            company=active,
            status__in=[BankGuarantee.Status.ACTIVE, BankGuarantee.Status.EXTENDED],
        ).order_by("expiry_date")
        bg_rows = []
        total_bg = Decimal("0.00")
        for bg in bg_qs:
            total_bg += bg.amount
            bg_rows.append(
                {
                    "id": str(bg.id),
                    "guarantee_number": bg.bg_number,
                    "bg_type": bg.bg_type,
                    "beneficiary_name": bg.beneficiary,
                    "amount": str(bg.amount),
                    "cash_margin_amount": str(bg.margin_amount),
                    "expiry_date": bg.expiry_date.isoformat(),
                    "status": bg.status,
                }
            )

        unmatched_count = BankStatementLine.objects.filter(
            company=active,
            match_status=BankStatementLine.MatchStatus.UNMATCHED,
        ).count()

        today = timezone.localdate()
        nrb_cfg = (
            NrbRegulatoryConfig.objects.filter(
                company=active, is_active=True, effective_from__lte=today
            )
            .filter(Q(effective_to__isnull=True) | Q(effective_to__gte=today))
            .order_by("-effective_from")
            .first()
        )

        return {
            "companies": company_list,
            "active_company": {
                "code": active.code,
                "name": active.name,
                "base_currency": active.base_currency,
            },
            "summary": {
                "total_bank_npr": str(total_bank.quantize(Decimal("0.01"))),
                "total_cash_npr": str(total_cash.quantize(Decimal("0.01"))),
                "total_loan_utilized_npr": str(total_loan_out.quantize(Decimal("0.01"))),
                "total_sanctioned_limit_npr": str(total_sanctioned.quantize(Decimal("0.01"))),
                "total_bg_exposure_npr": str(total_bg.quantize(Decimal("0.01"))),
                "unreconciled_statement_lines": unmatched_count,
                "nrb_threshold_pct": str(nrb_cfg.working_capital_cap_pct if nrb_cfg else Decimal("25.00")),
            },
            "banks": banks,
            "cash_accounts": cash_rows,
            "fx_rates": fx_rows,
            "facilities": facilities,
            "guarantees": bg_rows,
        }
    finally:
        close_old_connections()


@mcp.tool(
    name="open_treasury_hub",
    title="Maya Treasury Hub",
    description="Open the interactive Maya OS Banking, Cash, Multi-Currency & Nepal Loan Facilities Hub.",
    meta=PANE_META,
)
def open_treasury_hub(company_code: str | None = None) -> types.CallToolResult:
    data = _build_snapshot(company_code)
    comp = data["active_company"]
    s = data["summary"]
    label = f"{comp['name']} ({comp['code']})" if comp else "No Active Company"
    text = (
        f"Maya OS Treasury Hub — {label}\n"
        f"- Bank Liquidity: {s['total_bank_npr']}\n"
        f"- Cash Custody: {s['total_cash_npr']}\n"
        f"- Loans & OD/CC Utilized: {s['total_loan_utilized_npr']} / {s['total_sanctioned_limit_npr']}\n"
        f"- Active Bank Guarantees: {s['total_bg_exposure_npr']}\n"
        f"- Unreconciled Statement Lines: {s['unreconciled_statement_lines']}"
    )
    return types.CallToolResult(
        content=[types.TextContent(type="text", text=text)],
        structuredContent=data,
    )


@mcp.tool(
    name="get_treasury_snapshot",
    title="Get Treasury Snapshot",
    description="Fetch live bank, cash, FX, loan/OD/CC, and bank guarantee balances for the interactive UI.",
    meta=APP_ONLY_META,
)
def get_treasury_snapshot(company_code: str | None = None) -> types.CallToolResult:
    data = _build_snapshot(company_code)
    return types.CallToolResult(
        content=[types.TextContent(type="text", text="Snapshot refreshed")],
        structuredContent=data,
    )


@mcp.tool(
    name="calculate_loan_schedule",
    title="Calculate Nepal Loan / OD / CC Schedule",
    description="Compute Decimal-exact amortization schedule or CC Drawing Power and daily OD/CC interest.",
    meta=APP_ONLY_META,
)
def calculate_loan_schedule(
    mode: str = "TERM",
    principal: str = "15000000",
    annual_rate_pct: str = "10.75",
    tenure_months: int = 36,
    moratorium_months: int = 0,
    repayment_method: str = "EMI",
    eligible_stock_value: str = "12000000",
    stock_margin_pct: str = "25",
    eligible_receivables_value: str = "8000000",
    receivables_margin_pct: str = "30",
    sanctioned_limit: str = "20000000",
    overlimit_penal_rate_pct: str = "2.0",
) -> types.CallToolResult:
    q = Decimal("0.01")
    prin = Decimal(principal)
    rate = Decimal(annual_rate_pct)

    if mode == "REVOLVING":
        stock_val = Decimal(eligible_stock_value)
        stock_margin = Decimal(stock_margin_pct)
        rec_val = Decimal(eligible_receivables_value)
        rec_margin = Decimal(receivables_margin_pct)
        sanction = Decimal(sanctioned_limit)
        penal_pct = Decimal(overlimit_penal_rate_pct)

        eligible_stock = (stock_val * (Decimal("100") - stock_margin) / Decimal("100")).quantize(q, rounding=ROUND_HALF_UP)
        eligible_rec = (rec_val * (Decimal("100") - rec_margin) / Decimal("100")).quantize(q, rounding=ROUND_HALF_UP)
        drawing_power = (eligible_stock + eligible_rec).quantize(q)
        effective_limit = min(sanction, drawing_power).quantize(q)
        overlimit_amt = max(Decimal("0.00"), prin - effective_limit).quantize(q)
        regular_daily = (min(prin, effective_limit) * rate / Decimal("100") / Decimal("365")).quantize(q, rounding=ROUND_HALF_UP)
        penal_daily = (overlimit_amt * (rate + penal_pct) / Decimal("100") / Decimal("365")).quantize(q, rounding=ROUND_HALF_UP)
        payload = {
            "mode": "REVOLVING",
            "summary": {
                "eligible_stock_dp": str(eligible_stock),
                "eligible_receivables_dp": str(eligible_rec),
                "calculated_drawing_power": str(drawing_power),
                "effective_limit": str(effective_limit),
                "overlimit_amount": str(overlimit_amt),
                "regular_daily_interest": str(regular_daily),
                "penal_daily_interest": str(penal_daily),
                "total_daily_interest": str((regular_daily + penal_daily).quantize(q)),
            },
            "schedule": [],
        }
        return types.CallToolResult(
            content=[types.TextContent(type="text", text="Computed CC drawing power and OD daily interest.")],
            structuredContent=payload,
        )

    rows = generate_repayment_schedule(
        principal=prin,
        annual_rate_pct=rate,
        tenure_months=max(1, int(tenure_months)),
        start_date=date.today(),
        method=repayment_method,
        frequency="MONTHLY",
        moratorium_months=max(0, int(moratorium_months)),
    )
    total_interest = sum((r["interest_due"] for r in rows), Decimal("0.00")).quantize(q)
    total_payable = (prin + total_interest).quantize(q)
    first_emi = (rows[0]["principal_due"] + rows[0]["interest_due"]).quantize(q) if rows else Decimal("0.00")
    formatted = [
        {
            "installment_no": r["installment_no"],
            "due_date": r["due_date"].isoformat(),
            "opening_principal": str(r["opening_principal"]),
            "principal_component": str(r["principal_due"]),
            "interest_component": str(r["interest_due"]),
            "installment_total": str((r["principal_due"] + r["interest_due"]).quantize(q)),
            "closing_principal": str(r["closing_principal"]),
        }
        for r in rows
    ]
    payload = {
        "mode": "TERM",
        "summary": {
            "method": repayment_method,
            "installment_count": len(formatted),
            "first_installment": str(first_emi),
            "total_interest": str(total_interest),
            "total_repayment": str(total_payable),
        },
        "schedule": formatted,
    }
    return types.CallToolResult(
        content=[types.TextContent(type="text", text=f"Generated {len(formatted)} installments totaling {total_payable}.")],
        structuredContent=payload,
    )


if __name__ == "__main__":
    mcp.run()

