from datetime import date, timedelta
from decimal import Decimal
from django.core.management.base import BaseCommand
from django.db import transaction

from apps.accounts_rbac.constants import ROLE_PRESETS
from apps.accounts_rbac.models import ApprovalAuthority, CompanyMembership, Role, User
from apps.accounting.models import (
    Account,
    AccountRelationship,
    AdvanceRecord,
    EmployeeProfile,
    Party,
    PayrollLiability,
    StaffLoan,
    Voucher,
)
from apps.accounting.services import ApprovalService, PostingService, TallyConfigService, VoucherService
from apps.localization.bs_calendar import bs_to_ad
from apps.projects.models import CostCode, Project, Site
from apps.tenancy.models import Branch, Company, FiscalYear, TaxConfig


class Command(BaseCommand):
    help = "Seed Maya OS demo company, Nepal FY 2083/84, NFRS Chart of Accounts, projects, and sample vouchers."

    @transaction.atomic
    def handle(self, *args, **options):
        roles = {}
        for code, info in ROLE_PRESETS.items():
            role, _ = Role.objects.update_or_create(
                code=code,
                defaults={
                    "name": info["name"],
                    "description": info["description"],
                    "permissions": info["permissions"],
                    "is_system": True,
                    "default_dashboard_template": info.get("template", "DEFAULT"),
                },
            )
            roles[code] = role

        users_spec = [
            ("admin", "admin@mayaos.local", "Aarav Shrestha (Admin)", "Admin@1234", "COMPANY_ADMIN", True),
            ("finance", "finance@mayaos.local", "Sita Adhikari (Finance Mgr)", "Finance@1234", "FINANCE_MANAGER", False),
            ("accountant", "accountant@mayaos.local", "Ramesh Karki (Accountant)", "Account@1234", "ACCOUNTANT", False),
            ("supervisor", "site@mayaos.local", "Bikash Gurung (Site Sup)", "Site@1234", "SITE_SUPERVISOR", False),
        ]
        created_users = {}
        for uname, email, full_name, pw, role_code, is_super in users_spec:
            u, created = User.objects.get_or_create(
                username=uname,
                defaults={
                    "email": email,
                    "full_name": full_name,
                    "is_staff": is_super,
                    "is_superuser": is_super,
                },
            )
            if created:
                u.set_password(pw)
                u.save()
            created_users[uname] = (u, role_code)

        company, _ = Company.objects.get_or_create(
            code="HIPL",
            defaults={
                "name": "Himalayan Infrastructure Pvt. Ltd.",
                "registration_no": "REG-NP-2081-4492",
                "pan_vat_no": "601234567",
                "base_currency": "NPR",
                "calendar_preference": Company.CalendarPref.BS,
                "default_vat_rate": Decimal("13.00"),
                "nfrs_enabled": True,
            },
        )

        ho_branch, _ = Branch.objects.get_or_create(
            company=company,
            code="HO-KTM",
            defaults={"name": "Kathmandu Head Office", "address": "Thapathali, Kathmandu", "is_head_office": True},
        )
        Branch.objects.get_or_create(
            company=company,
            code="BR-PKR",
            defaults={"name": "Pokhara Regional Office", "address": "Lakeside, Pokhara", "is_head_office": False},
        )

        for uname, (u, role_code) in created_users.items():
            CompanyMembership.objects.get_or_create(
                user=u,
                company=company,
                defaults={"role": roles[role_code], "is_default": True, "is_active": True},
            )

        # Nepal FY 2083/84 (Shrawan 1, 2083 to Ashadh end, 2084)
        fy_start = bs_to_ad(2083, 4, 1)
        fy_end = bs_to_ad(2084, 3, 31)
        fy, _ = FiscalYear.objects.get_or_create(
            company=company,
            name="2083/84",
            defaults={"start_date": fy_start, "end_date": fy_end, "is_current": True},
        )
        fy.generate_nepal_periods(2083)

        # Tax Configs
        for code, name, ttype, rate in [
            ("VAT_13", "Nepal Standard VAT 13%", TaxConfig.TaxType.VAT, Decimal("13.00")),
            ("TDS_CON_1_5", "Construction Contract TDS 1.5%", TaxConfig.TaxType.TDS, Decimal("1.50")),
            ("TDS_SRV_15", "Non-VAT Service TDS 15%", TaxConfig.TaxType.TDS, Decimal("15.00")),
            ("TDS_RENT_10", "Equipment/Property Rent TDS 10%", TaxConfig.TaxType.TDS, Decimal("10.00")),
        ]:
            TaxConfig.objects.get_or_create(
                company=company,
                code=code,
                defaults={"name": name, "tax_type": ttype, "rate": rate},
            )

        # Chart of Accounts (NFRS aligned)
        coa_spec = [
            ("1000", "Assets", "ASSET", "", True, False, "0.00", "0.00", None),
            ("1010", "Cash in Hand — Site & HO", "ASSET", "NAS 07", False, False, "250000.00", "0.00", "1000"),
            ("1020", "Nabil Bank Ltd. — NPR Current", "ASSET", "NAS 07", False, False, "8500000.00", "0.00", "1000"),
            ("1100", "Accounts Receivable — Clients", "ASSET", "NFRS 15", False, True, "1200000.00", "0.00", "1000"),
            ("1200", "Site Material Inventory", "ASSET", "NAS 02", False, False, "950000.00", "0.00", "1000"),
            ("2000", "Liabilities", "LIABILITY", "", True, False, "0.00", "0.00", None),
            ("2010", "Accounts Payable — Suppliers", "LIABILITY", "NAS 32", False, True, "0.00", "750000.00", "2000"),
            ("2110", "VAT Payable (13%)", "LIABILITY", "IRD VAT", False, False, "0.00", "0.00", "2000"),
            ("2120", "TDS Payable (Sec 89)", "LIABILITY", "IRD TDS", False, False, "0.00", "0.00", "2000"),
            ("2200", "Retention Payable", "LIABILITY", "NFRS 15", False, False, "0.00", "150000.00", "2000"),
            ("3000", "Equity", "EQUITY", "", True, False, "0.00", "0.00", None),
            ("3010", "Paid-Up Share Capital", "EQUITY", "NAS 01", False, False, "0.00", "10000000.00", "3000"),
            ("4000", "Revenue", "INCOME", "", True, False, "0.00", "0.00", None),
            ("4010", "Construction Contract Revenue", "INCOME", "NFRS 15", False, False, "0.00", "0.00", "4000"),
            ("5000", "Direct & Operating Expenses", "EXPENSE", "", True, False, "0.00", "0.00", None),
            ("5010", "Construction Material Expense", "EXPENSE", "NAS 02", False, False, "0.00", "0.00", "5000"),
            ("5020", "Site Labor & Wages", "EXPENSE", "NAS 19", False, False, "0.00", "0.00", "5000"),
            ("5030", "Heavy Equipment Rental", "EXPENSE", "NFRS 16", False, False, "0.00", "0.00", "5000"),
            ("5040", "Subcontractor Works", "EXPENSE", "NFRS 15", False, False, "0.00", "0.00", "5000"),
            ("5050", "Site Overheads & Transport", "EXPENSE", "NAS 01", False, False, "0.00", "0.00", "5000"),
        ]
        accounts = {}
        for code, name, atype, nfrs, is_grp, is_ctrl, od, oc, parent_code in coa_spec:
            acc, _ = Account.objects.get_or_create(
                company=company,
                code=code,
                defaults={
                    "name": name,
                    "account_type": atype,
                    "nfrs_mapping": nfrs,
                    "is_group": is_grp,
                    "is_control_account": is_ctrl,
                    "opening_debit": Decimal(od),
                    "opening_credit": Decimal(oc),
                    "parent": accounts.get(parent_code) if parent_code else None,
                },
            )
            accounts[code] = acc

        # Projects, Sites, Cost Codes
        prj1, _ = Project.objects.get_or_create(
            company=company,
            code="PRJ-01",
            defaults={
                "name": "Pokhara Ring Road Package II",
                "client_name": "Department of Roads, Nepal",
                "location": "Pokhara, Kaski",
                "contract_amount": Decimal("48000000.00"),
                "budget_amount": Decimal("38500000.00"),
                "start_date": fy_start,
                "status": Project.Status.ACTIVE,
            },
        )
        prj2, _ = Project.objects.get_or_create(
            company=company,
            code="PRJ-02",
            defaults={
                "name": "Trishuli Hydro Access Bridge",
                "client_name": "Trishuli Jal Vidhyut Co.",
                "location": "Rasuwa",
                "contract_amount": Decimal("22000000.00"),
                "budget_amount": Decimal("17800000.00"),
                "start_date": fy_start,
                "status": Project.Status.ACTIVE,
            },
        )
        site1, _ = Site.objects.get_or_create(
            project=prj1, code="SITE-A", defaults={"name": "Chhorepatan Asphalt Plant", "location": "Pokhara-17"}
        )
        Site.objects.get_or_create(
            project=prj2, code="SITE-B", defaults={"name": "Betrawati Bridge Abutment", "location": "Rasuwa"}
        )

        cc_mat, _ = CostCode.objects.get_or_create(
            company=company, code="CC-MAT", defaults={"name": "Cement, Steel & Aggregates", "category": CostCode.Category.MATERIAL}
        )
        cc_lab, _ = CostCode.objects.get_or_create(
            company=company, code="CC-LAB", defaults={"name": "Skilled & Unskilled Site Labor", "category": CostCode.Category.LABOR}
        )
        cc_eqp, _ = CostCode.objects.get_or_create(
            company=company, code="CC-EQP", defaults={"name": "Excavator & Dumper Usage", "category": CostCode.Category.EQUIPMENT}
        )
        cc_sub, _ = CostCode.objects.get_or_create(
            company=company, code="CC-SUB", defaults={"name": "Subcontract Earthworks", "category": CostCode.Category.SUBCONTRACT}
        )

        if Voucher.objects.filter(company=company).count() < 5:
            admin_user = created_users["admin"][0]
            finance_user = created_users["finance"][0]
            acc_user = created_users["accountant"][0]
            sup_user = created_users["supervisor"][0]

            def post_sample(vtype, vdate, proj, party, narr, lines, idemp):
                if Voucher.objects.filter(company=company, idempotency_key=idemp).exists():
                    return
                v = VoucherService.create_draft(
                    company=company,
                    user=acc_user,
                    data={
                        "voucher_type": vtype,
                        "voucher_date": vdate,
                        "branch": ho_branch,
                        "project": proj,
                        "party_name": party,
                        "narration": narr,
                        "idempotency_key": idemp,
                    },
                    lines_data=lines,
                )
                VoucherService.submit_voucher(voucher=v, user=acc_user)
                ApprovalService.approve_voucher(voucher=v, user=finance_user)
                PostingService.post_voucher(voucher=v, user=finance_user)

            # Historical posted entries across Aug-Oct 2026 (Shrawan-Kartik 2083)
            post_sample(
                Voucher.VoucherType.SALES,
                date(2026, 8, 18),
                prj1,
                "Department of Roads, Nepal",
                "Mobilization & IPC-00 progress billing",
                [
                    {"account": accounts["1100"], "debit": Decimal("1450000.00"), "credit": Decimal("0.00")},
                    {"account": accounts["4010"], "debit": Decimal("0.00"), "credit": Decimal("1450000.00"), "project": prj1},
                ],
                "seed-aug-sales",
            )
            post_sample(
                Voucher.VoucherType.PURCHASE,
                date(2026, 8, 22),
                prj1,
                "Shivam Cement Distributors",
                "Bulk OPC 53 grade cement delivery",
                [
                    {"account": accounts["5010"], "debit": Decimal("620000.00"), "credit": Decimal("0.00"), "project": prj1, "cost_code": cc_mat},
                    {"account": accounts["2010"], "debit": Decimal("0.00"), "credit": Decimal("620000.00")},
                ],
                "seed-aug-pur",
            )
            post_sample(
                Voucher.VoucherType.PAYMENT,
                date(2026, 9, 14),
                prj2,
                "Himalayan Earthmovers",
                "Excavator & rock breaker rental — Sep",
                [
                    {"account": accounts["5030"], "debit": Decimal("380000.00"), "credit": Decimal("0.00"), "project": prj2, "cost_code": cc_eqp},
                    {"account": accounts["1020"], "debit": Decimal("0.00"), "credit": Decimal("380000.00")},
                ],
                "seed-sep-eqp",
            )
            post_sample(
                Voucher.VoucherType.SALES,
                date(2026, 10, 12),
                prj2,
                "Trishuli Jal Vidhyut Co.",
                "Bridge abutment foundation billing",
                [
                    {"account": accounts["1100"], "debit": Decimal("2100000.00"), "credit": Decimal("0.00")},
                    {"account": accounts["4010"], "debit": Decimal("0.00"), "credit": Decimal("2100000.00"), "project": prj2},
                ],
                "seed-oct-sales",
            )
            post_sample(
                Voucher.VoucherType.PURCHASE,
                date(2026, 10, 20),
                prj2,
                "Annapurna Subcontractors",
                "Piling & gabion wall subcontract bill",
                [
                    {"account": accounts["5040"], "debit": Decimal("540000.00"), "credit": Decimal("0.00"), "project": prj2, "cost_code": cc_sub},
                    {"account": accounts["2010"], "debit": Decimal("0.00"), "credit": Decimal("540000.00")},
                ],
                "seed-oct-sub",
            )
            post_sample(
                Voucher.VoucherType.PAYMENT,
                date(2026, 11, 20),
                prj1,
                "Panchakanya Steel Traders",
                "TMT Rebar & OPC Cement purchase for Pokhara Ring Road culverts",
                [
                    {"account": accounts["5010"], "debit": Decimal("450000.00"), "credit": Decimal("0.00"), "project": prj1, "site": site1, "cost_code": cc_mat},
                    {"account": accounts["1020"], "debit": Decimal("0.00"), "credit": Decimal("450000.00")},
                ],
                "seed-nov-mat",
            )
            post_sample(
                Voucher.VoucherType.RECEIPT,
                date(2026, 11, 25),
                prj1,
                "Department of Roads, Nepal",
                "IPC-01 Running Bill receipt against Pokhara Ring Road",
                [
                    {"account": accounts["1020"], "debit": Decimal("1850000.00"), "credit": Decimal("0.00")},
                    {"account": accounts["4010"], "debit": Decimal("0.00"), "credit": Decimal("1850000.00"), "project": prj1},
                ],
                "seed-nov-rec",
            )

            # Pending approval vouchers
            if not Voucher.objects.filter(company=company, idempotency_key="seed-pend-1").exists():
                vp1 = VoucherService.create_draft(
                    company=company,
                    user=sup_user,
                    data={
                        "voucher_type": Voucher.VoucherType.PAYMENT,
                        "voucher_date": date(2026, 11, 28),
                        "branch": ho_branch,
                        "project": prj1,
                        "site": site1,
                        "party_name": "Site Gang Labor Muster Roll",
                        "narration": "Weekly site masonry & shuttering wages (pending finance approval)",
                        "idempotency_key": "seed-pend-1",
                    },
                    lines_data=[
                        {"account": accounts["5020"], "debit": Decimal("125000.00"), "credit": Decimal("0.00"), "project": prj1, "site": site1, "cost_code": cc_lab},
                        {"account": accounts["1010"], "debit": Decimal("0.00"), "credit": Decimal("125000.00")},
                    ],
                )
                VoucherService.submit_voucher(voucher=vp1, user=sup_user)

            if not Voucher.objects.filter(company=company, idempotency_key="seed-pend-2").exists():
                vp2 = VoucherService.create_draft(
                    company=company,
                    user=acc_user,
                    data={
                        "voucher_type": Voucher.VoucherType.PURCHASE,
                        "voucher_date": date(2026, 11, 27),
                        "branch": ho_branch,
                        "project": prj2,
                        "party_name": "Nepal Bitumen & Asphalt Co.",
                        "narration": "High-value bitumen emulsion batch (awaiting Finance Manager)",
                        "idempotency_key": "seed-pend-2",
                    },
                    lines_data=[
                        {"account": accounts["5010"], "debit": Decimal("285000.00"), "credit": Decimal("0.00"), "project": prj2, "cost_code": cc_mat},
                        {"account": accounts["2010"], "debit": Decimal("0.00"), "credit": Decimal("285000.00")},
                    ],
                )
                VoucherService.submit_voucher(voucher=vp2, user=acc_user)

        if not ApprovalAuthority.objects.filter(company=company).exists():
            ApprovalAuthority.objects.create(
                company=company,
                role=roles["FINANCE_MANAGER"],
                voucher_type="ALL",
                currency="NPR",
                min_amount=Decimal("0.00"),
                max_amount=Decimal("500000.00"),
                approval_level=1,
            )
            ApprovalAuthority.objects.create(
                company=company,
                role=roles["FINANCE_DIRECTOR"],
                voucher_type="ALL",
                currency="NPR",
                min_amount=Decimal("0.00"),
                max_amount=Decimal("2500000.00"),
                approval_level=2,
            )
            ApprovalAuthority.objects.create(
                company=company,
                role=roles["COMPANY_ADMIN"],
                voucher_type="ALL",
                currency="NPR",
                min_amount=Decimal("0.00"),
                max_amount=None,
                approval_level=3,
            )

        # Seed Banking, Multi-Currency, Cheques, NRB Rules & Sample Loans
        from apps.banking.models import Bank, BankAccount, BankBranch, CashAccount, ChequeBook
        from apps.banking.services import BankingService
        from apps.currency.models import ExchangeRate
        from apps.currency.services import ensure_default_currencies
        from apps.loans.models import BankFacility, BankGuarantee, LoanCollateral, NrbRegulatoryConfig, RevolvingProductConfig
        from apps.loans.services import LoanService

        company.multi_currency_enabled = True
        company.save(update_fields=["multi_currency_enabled"])
        ensure_default_currencies(company)
        ExchangeRate.objects.get_or_create(
            company=company,
            from_currency="USD",
            to_currency="NPR",
            effective_date=date(2026, 11, 28),
            rate_source=ExchangeRate.Source.NRB_REF,
            bank_name="",
            defaults={"buy_rate": Decimal("134.500000"), "sell_rate": Decimal("135.100000"), "mid_rate": Decimal("134.800000")},
        )
        ExchangeRate.objects.get_or_create(
            company=company,
            from_currency="INR",
            to_currency="NPR",
            effective_date=date(2026, 11, 28),
            rate_source=ExchangeRate.Source.NRB_REF,
            bank_name="",
            defaults={"buy_rate": Decimal("1.600000"), "sell_rate": Decimal("1.601500"), "mid_rate": Decimal("1.600000")},
        )

        nabil, _ = Bank.objects.get_or_create(
            company=company, short_code="NABIL", defaults={"name": "Nabil Bank Ltd.", "swift_code": "NARBNPKA"}
        )
        nabil_br, _ = BankBranch.objects.get_or_create(
            bank=nabil, branch_code="THP", defaults={"name": "Thapathali Corporate Branch", "address": "Kathmandu"}
        )
        if not BankAccount.objects.filter(company=company).exists():
            from apps.banking.security import encrypt_account_number, hash_account_number, mask_account_number

            ba_main = BankAccount.objects.create(
                company=company,
                bank_branch=nabil_br,
                branch=ho_branch,
                account_name="Nabil Main Operations NPR",
                account_number_masked=mask_account_number("01010175001234"),
                account_number_encrypted=encrypt_account_number("01010175001234"),
                account_number_hash=hash_account_number("01010175001234"),
                account_type=BankAccount.AccountType.CURRENT,
                purpose=BankAccount.Purpose.GENERAL,
                currency="NPR",
                gl_account=accounts["1020"],
                opening_balance=Decimal("8500000.00"),
            )
            BankingService.create_bank_account(
                company=company,
                user=created_users["admin"][0],
                bank_branch=nabil_br,
                account_name="Pokhara Ring Road Collection",
                account_number="01010175008899",
                account_type=BankAccount.AccountType.CURRENT,
                purpose=BankAccount.Purpose.PROJECT_COLLECTION,
                currency="NPR",
                opening_balance=Decimal("0.00"),
                project=prj1,
            )
            CashAccount.objects.get_or_create(
                company=company,
                code="CASH-HO",
                defaults={
                    "name": "Head Office Main Cash",
                    "cash_type": CashAccount.CashType.HEAD_OFFICE,
                    "gl_account": accounts["1010"],
                    "custodian": created_users["accountant"][0],
                    "branch": ho_branch,
                },
            )
            BankingService.create_cash_account(
                company=company,
                user=created_users["admin"][0],
                code="IMPREST-SITEA",
                name="Site-A Chhorepatan Imprest Cash",
                cash_type=CashAccount.CashType.IMPREST,
                currency="NPR",
                imprest_limit=Decimal("150000.00"),
                project=prj1,
                site=site1,
                custodian=created_users["supervisor"][0],
            )
            if not ChequeBook.objects.filter(bank_account=ba_main).exists():
                BankingService.create_cheque_book(
                    company=company,
                    bank_account=ba_main,
                    book_code="CHQ-2083-A",
                    prefix="NB-",
                    start_number=1001,
                    end_number=1010,
                    issued_date=date(2026, 8, 1),
                )

            NrbRegulatoryConfig.objects.get_or_create(
                company=company,
                directive_code="NRB-WC-2083",
                defaults={
                    "title": "NRB Working Capital & Unified Directive 2083",
                    "effective_from": date(2026, 7, 16),
                    "working_capital_cap_pct": Decimal("25.00"),
                    "od_max_limit_npr": Decimal("5000000.00"),
                    "cc_default_haircut_pct": Decimal("25.00"),
                    "penal_interest_cap_pct": Decimal("2.00"),
                    "published_base_rate": Decimal("8.25"),
                },
            )
            RevolvingProductConfig.objects.get_or_create(
                company=company,
                product_kind=RevolvingProductConfig.ProductKind.OVERDRAFT,
                defaults={"requires_drawing_power": False, "max_tenure_days": 365, "allow_clean_overdraft": True},
            )
            RevolvingProductConfig.objects.get_or_create(
                company=company,
                product_kind=RevolvingProductConfig.ProductKind.CASH_CREDIT,
                defaults={"requires_drawing_power": True, "stock_haircut_pct": Decimal("25.00"), "receivable_haircut_pct": Decimal("30.00")},
            )

            tl = LoanService.create_facility(
                company=company,
                user=created_users["admin"][0],
                data={
                    "bank_account": ba_main,
                    "project": prj1,
                    "facility_code": "TL-EQP-01",
                    "facility_name": "Caterpillar Excavator Equipment Loan",
                    "facility_type": BankFacility.FacilityType.EQUIPMENT_LOAN,
                    "sanction_ref": "NABIL/EQP/2083/102",
                    "sanction_date": date(2026, 8, 1),
                    "maturity_date": date(2029, 8, 1),
                    "sanctioned_limit": Decimal("4000000.00"),
                    "base_rate": Decimal("8.25"),
                    "premium_rate": Decimal("2.25"),
                    "tenure_months": 36,
                    "schedule_method": BankFacility.ScheduleMethod.EMI,
                },
            )
            LoanService.disburse_loan(
                facility=tl,
                user=created_users["admin"][0],
                disbursement_date=date(2026, 8, 5),
                amount=Decimal("3200000.00"),
                reference_no="DISB-001",
            )
            LoanCollateral.objects.create(
                company=company,
                facility=tl,
                security_type=LoanCollateral.SecurityType.EQUIPMENT_VEHICLE,
                description="CAT 320D Hydraulic Excavator Hypothecation",
                owner_name="Himalayan Infrastructure Pvt. Ltd.",
                assessed_value=Decimal("5200000.00"),
                lien_mortgage_ref="HYP-2083-441",
                insurance_policy_no="SIC-EQ-99812",
                insurance_expiry=date(2027, 8, 1),
            )

            LoanService.issue_bank_guarantee(
                company=company,
                user=created_users["admin"][0],
                data={
                    "bank_account": ba_main,
                    "project": prj1,
                    "bg_number": "BG-NABIL-2083-01",
                    "bg_type": BankGuarantee.BGType.PERFORMANCE,
                    "beneficiary": "Department of Roads, Nepal",
                    "amount": Decimal("2400000.00"),
                    "margin_percent": Decimal("10.00"),
                    "commission_amount": Decimal("18000.00"),
                    "issue_date": date(2026, 8, 10),
                    "expiry_date": date(2027, 12, 31),
                },
            )

        # Seed Centralized Document, Print & Delivery Engine
        from apps.document_engine.models import (
            DocumentDeliveryChannel,
            DocumentDeliveryRule,
            DocumentRecord,
            DocumentSequence,
            DocumentSignatureConfig,
            DocumentTemplate,
            DocumentTemplateVersion,
            DocumentType,
            ExportProfile,
            PrintProfile,
        )
        from django.utils import timezone
        from apps.document_engine.services.document_registry import ensure_default_document_types
        from apps.document_engine.services.template_resolver import DEFAULT_LAYOUT_SCHEMA

        ensure_default_document_types()
        PrintProfile.objects.get_or_create(
            company=company,
            document_type=None,
            is_default=True,
            defaults={"name": "HIPL Standard A4 Bilingual", "language": "BILINGUAL", "date_format": "BOTH", "accent_color": "#0f766e"},
        )
        ExportProfile.objects.get_or_create(
            company=company,
            document_type=None,
            is_default=True,
            defaults={"name": "HIPL Enterprise Workbook", "freeze_panes": True, "auto_filter": True, "include_charts": True},
        )
        DocumentSignatureConfig.objects.get_or_create(
            company=company,
            document_type=None,
            defaults={
                "slots": [
                    {"role": "Prepared By", "label": "Prepared By"},
                    {"role": "Checked By", "label": "Checked By"},
                    {"role": "Approved By", "label": "Authorized By"},
                ]
            },
        )

        for code_pfx, doc_code in [("INV-2083-", "SALES_INVOICE"), ("PV-2083-", "PAYMENT_VOUCHER"), ("RA-2083-", "RA_BILL"), ("DC-2083-", "DELIVERY_CHALLAN")]:
            dt_obj = DocumentType.objects.filter(code=doc_code).first()
            if not dt_obj:
                continue
            DocumentSequence.objects.get_or_create(
                company=company,
                branch=None,
                fiscal_year=fy,
                document_type=dt_obj,
                phase=DocumentSequence.Phase.FINAL,
                defaults={"prefix": code_pfx, "digit_length": 5, "last_number": 1},
            )
            tpl, created_tpl = DocumentTemplate.objects.get_or_create(
                company=company,
                branch=None,
                document_type=dt_obj,
                code=f"DEFAULT-{doc_code}",
                defaults={"name": f"{dt_obj.name} — Nepal Standard", "is_default": True, "is_system": True},
            )
            if created_tpl:
                ver = DocumentTemplateVersion.objects.create(
                    template=tpl,
                    version_number=1,
                    status=DocumentTemplateVersion.Status.APPROVED,
                    effective_from=date(2026, 7, 16),
                    layout_schema=DEFAULT_LAYOUT_SCHEMA,
                    change_notes="Initial enterprise default template",
                    created_by=created_users["admin"][0],
                    approved_by=created_users["admin"][0],
                    approved_at=timezone.now(),
                )
                tpl.active_version = ver
                tpl.save(update_fields=["active_version"])

        ra_type = DocumentType.objects.filter(code="RA_BILL").first()
        dc_type = DocumentType.objects.filter(code="DELIVERY_CHALLAN").first()
        if ra_type and not DocumentRecord.objects.filter(company=company, document_type=ra_type).exists():
            DocumentRecord.objects.create(
                company=company,
                branch=ho_branch,
                fiscal_year=fy,
                document_type=ra_type,
                source_model="document_engine.DocumentRecord",
                source_id="RA-2083-00001",
                document_number="RA-2083-00001",
                issue_date=date(2026, 11, 20),
                bs_date="2083-08-04",
                party_name="Department of Urban Development & Building",
                project=prj1,
                currency="NPR",
                total_amount=Decimal("1850000.00"),
                status=DocumentRecord.Status.ISSUED,
                payload_data={
                    "title": "Running Account Bill #01 — Ring Road Flyover",
                    "rows": [
                        {"sn": 1, "description": "Pile Cap Concrete M35 (Cum)", "qty": 120, "rate": 12500, "amount": 1500000},
                        {"sn": 2, "description": "Reinforcement Bar Bending & Fixing (MT)", "qty": 2.5, "rate": 140000, "amount": 350000},
                    ],
                    "totals": {"subtotal": 1850000, "tax_label": "VAT 13%", "tax_amount": 240500, "grand_total": 2090500},
                    "narration": "Certified per Measurement Book MB-01.",
                },
                created_by=created_users["admin"][0],
            )
        if dc_type and not DocumentRecord.objects.filter(company=company, document_type=dc_type).exists():
            DocumentRecord.objects.create(
                company=company,
                branch=ho_branch,
                fiscal_year=fy,
                document_type=dc_type,
                source_model="document_engine.DocumentRecord",
                source_id="DC-2083-00001",
                document_number="DC-2083-00001",
                issue_date=date(2026, 11, 22),
                bs_date="2083-08-06",
                party_name="HIPL Site A Store — Kalanki",
                project=prj1,
                currency="NPR",
                total_amount=Decimal("420000.00"),
                status=DocumentRecord.Status.ISSUED,
                payload_data={
                    "title": "Material Delivery Challan",
                    "rows": [
                        {"sn": 1, "description": "OPC 53 Grade Cement (Bags)", "qty": 600, "rate": 700, "amount": 420000},
                    ],
                    "totals": {"subtotal": 420000, "tax_label": "Dispatch Fee", "tax_amount": 0, "grand_total": 420000},
                    "narration": "Dispatched via Truck Ba 3 Kha 4192; Gate Pass verified.",
                },
                created_by=created_users["admin"][0],
            )

        portal_ch, _ = DocumentDeliveryChannel.objects.get_or_create(
            company=company,
            channel_type=DocumentDeliveryChannel.ChannelType.PORTAL,
            name="Customer Portal Expiring Link",
            defaults={"is_enabled": True, "sender_identity": "portal@mayaos.local"},
        )
        inv_type = DocumentType.objects.filter(code="SALES_INVOICE").first()
        if inv_type:
            DocumentDeliveryRule.objects.get_or_create(
                company=company,
                document_type=inv_type,
                event_trigger=DocumentDeliveryRule.EventTrigger.SALES_INVOICE_APPROVED,
                defaults={"channel": portal_ch, "auto_generate_pdf": True, "auto_send": False},
            )

        # Seed Advanced Construction COA Control Roles, Subledgers, Policies, Themes & Operational Docs
        from apps.accounting.models import (
            AccountingPolicy,
            BoqItem,
            CostCenter,
            Department,
            EquipmentAsset,
            Party,
            PostingRule,
            VoucherThemeConfig,
            WorkPackage,
        )
        from apps.construction_ops.models import OperationalDocument
        from apps.construction_ops.services import ConstructionOpsService

        role_updates = {
            "1010": (Account.ControlRole.CASH, Account.AccountClass.ASSET, False),
            "1020": (Account.ControlRole.BANK, Account.AccountClass.ASSET, False),
            "1100": (Account.ControlRole.SUNDRY_DEBTORS, Account.AccountClass.ASSET, True),
            "1200": (Account.ControlRole.INVENTORY, Account.AccountClass.ASSET, False),
            "2010": (Account.ControlRole.SUNDRY_CREDITORS, Account.AccountClass.LIABILITY, True),
            "2110": (Account.ControlRole.OUTPUT_VAT, Account.AccountClass.LIABILITY, False),
            "2120": (Account.ControlRole.TDS_PAYABLE, Account.AccountClass.LIABILITY, False),
            "2200": (Account.ControlRole.RETENTION_PAYABLE, Account.AccountClass.LIABILITY, False),
        }
        for code, (c_role, a_cls, req_sub) in role_updates.items():
            if code in accounts:
                Account.objects.filter(id=accounts[code].id).update(
                    control_role=c_role, account_class=a_cls, requires_subledger=req_sub, is_control_account=req_sub
                )

        ext_coa = [
            ("1150", "Supplier & Mobilization Advances", "ASSET", Account.AccountClass.ASSET, Account.ControlRole.SUPPLIER_ADVANCE, "1000"),
            ("1160", "Client Retention Receivable", "ASSET", Account.AccountClass.ASSET, Account.ControlRole.RETENTION_RECEIVABLE, "1000"),
            ("1170", "Employee & Staff Advances", "ASSET", Account.AccountClass.ASSET, Account.ControlRole.EMPLOYEE_ADVANCE, "1000"),
            ("1175", "Staff Loan Receivable", "ASSET", Account.AccountClass.ASSET, Account.ControlRole.STAFF_LOAN_RECEIVABLE, "1000"),
            ("1250", "Recoverable Input VAT (13%)", "ASSET", Account.AccountClass.ASSET, Account.ControlRole.INPUT_VAT, "1000"),
            ("1400", "Project Work-in-Progress (WIP)", "ASSET", Account.AccountClass.ASSET, Account.ControlRole.PROJECT_WIP, "1000"),
            ("1510", "Plant, Machinery & Heavy Equipment", "ASSET", Account.AccountClass.ASSET, Account.ControlRole.NONE, "1000"),
            ("1590", "Accumulated Depreciation — Equipment", "ASSET", Account.AccountClass.CONTRA_ASSET, Account.ControlRole.ACCUM_DEPRECIATION, "1000"),
            ("2020", "Subcontractor Payable Control", "LIABILITY", Account.AccountClass.LIABILITY, Account.ControlRole.SUBCONTRACTOR_PAYABLE, "2000"),
            ("2030", "Employee Payables Control", "LIABILITY", Account.AccountClass.LIABILITY, Account.ControlRole.EMPLOYEE_PAYABLE, "2000"),
            ("2035", "Wages & Payroll Payable", "LIABILITY", Account.AccountClass.LIABILITY, Account.ControlRole.WAGES_PAYABLE, "2000"),
            ("2040", "Employee Reimbursement Payable", "LIABILITY", Account.AccountClass.LIABILITY, Account.ControlRole.EMPLOYEE_REIMBURSEMENT, "2000"),
            ("2045", "PF, SSF & CIT Statutory Payable", "LIABILITY", Account.AccountClass.LIABILITY, Account.ControlRole.PF_SSF_PAYABLE, "2000"),
            ("2070", "Customer Mobilization Advance Liability", "LIABILITY", Account.AccountClass.LIABILITY, Account.ControlRole.CUSTOMER_ADVANCE, "2000"),
            ("2080", "Outstanding / Accrued Expenses Payable", "LIABILITY", Account.AccountClass.LIABILITY, Account.ControlRole.OUTSTANDING_EXPENSES, "2000"),
            ("2090", "Goods Received Not Invoiced (GRNI)", "LIABILITY", Account.AccountClass.LIABILITY, Account.ControlRole.GRNI, "2000"),
            ("4020", "Commercial Sales Revenue", "INCOME", Account.AccountClass.INCOME, Account.ControlRole.NONE, "4000"),
            ("4030", "Equipment Rental & Other Income", "INCOME", Account.AccountClass.GAIN, Account.ControlRole.OTHER_INCOME, "4000"),
            ("4050", "Discounts Allowed (Contra Income)", "INCOME", Account.AccountClass.CONTRA_INCOME, Account.ControlRole.NONE, "4000"),
            ("5060", "Diesel & Fuel Expense", "EXPENSE", Account.AccountClass.EXPENSE, Account.ControlRole.DIRECT_EXPENSES, "5000"),
            ("5070", "Quality Testing & Site Inspection Cost", "EXPENSE", Account.AccountClass.EXPENSE, Account.ControlRole.DIRECT_EXPENSES, "5000"),
            ("6000", "Office & Administrative Expenses A/C", "EXPENSE", Account.AccountClass.EXPENSE, Account.ControlRole.OFFICE_EXPENSES, None),
            ("6010", "Office Rent Expense", "EXPENSE", Account.AccountClass.EXPENSE, Account.ControlRole.NONE, "6000"),
            ("6020", "Electricity & Power Expense", "EXPENSE", Account.AccountClass.EXPENSE, Account.ControlRole.NONE, "6000"),
            ("6030", "Internet & Communication Expense", "EXPENSE", Account.AccountClass.EXPENSE, Account.ControlRole.NONE, "6000"),
            ("6040", "Telephone & Mobile Expense", "EXPENSE", Account.AccountClass.EXPENSE, Account.ControlRole.NONE, "6000"),
            ("6045", "Printing & Stationery Expense", "EXPENSE", Account.AccountClass.EXPENSE, Account.ControlRole.NONE, "6000"),
            ("6050", "Depreciation Expense", "EXPENSE", Account.AccountClass.EXPENSE, Account.ControlRole.DEPRECIATION_EXP, "6000"),
            ("6060", "Repairs & Office Maintenance", "EXPENSE", Account.AccountClass.EXPENSE, Account.ControlRole.NONE, "6000"),
            ("6090", "Losses & Bad Debt Write-Off", "EXPENSE", Account.AccountClass.LOSS, Account.ControlRole.LOSS_WRITE_OFF, "6000"),
        ]
        for code, name, atype, a_cls, c_role, p_code in ext_coa:
            is_grp = code == "6000"
            acc, _ = Account.objects.get_or_create(
                company=company,
                code=code,
                defaults={
                    "name": name,
                    "account_type": atype,
                    "account_class": a_cls,
                    "control_role": c_role,
                    "is_group": is_grp,
                    "parent": accounts.get(p_code),
                },
            )
            accounts[code] = acc
        # Ensure 1010/1020/5000/6000 carry explicit roles & group hierarchy cleanly
        Account.objects.filter(company=company, code="1010").update(control_role=Account.ControlRole.CASH)
        Account.objects.filter(company=company, code="1020").update(control_role=Account.ControlRole.BANK)
        Account.objects.filter(company=company, code="5000").update(control_role=Account.ControlRole.DIRECT_EXPENSES)
        if "6000" in accounts:
            Account.objects.filter(company=company, code="6000").update(is_group=True, control_role=Account.ControlRole.OFFICE_EXPENSES)
            Account.objects.filter(company=company, code__in=["6010", "6050"]).update(parent=accounts["6000"])
        for acc_code, tkind, xsel, counter_code, req_prj, req_sub, req_rsn in [
            ("2010", AccountRelationship.TargetKind.SUPPLIER_CONTRACTOR, "INVOICE_ALLOCATION", "1020", False, True, True),
            ("2020", AccountRelationship.TargetKind.SUPPLIER_CONTRACTOR, "INVOICE_ALLOCATION", "1020", False, True, True),
            ("1100", AccountRelationship.TargetKind.CUSTOMER_CLIENT, "RECEIVABLE_ALLOCATION", "4010", False, True, True),
            ("2030", AccountRelationship.TargetKind.EMPLOYEE, "PAYROLL_REF", "1170", False, True, False),
            ("2035", AccountRelationship.TargetKind.EMPLOYEE, "PAYROLL_REF", "1170", False, True, False),
            ("1170", AccountRelationship.TargetKind.EMPLOYEE_ADVANCE, "ADVANCE_REF", "2035", False, False, False),
            ("1175", AccountRelationship.TargetKind.STAFF_LOAN, "LOAN_REF", "2035", False, False, False),
            ("1150", AccountRelationship.TargetKind.SUPPLIER_ADVANCE, "ADVANCE_REF", "2010", False, False, False),
            ("2070", AccountRelationship.TargetKind.CUSTOMER_ADVANCE, "ADVANCE_REF", "1100", False, False, False),
            ("1400", AccountRelationship.TargetKind.PROJECT_WIP, "PROJECT_SITE_COST_CODE", "1200", True, False, False),
            ("6000", AccountRelationship.TargetKind.CHILD_EXPENSE, "DEPARTMENT_PROJECT", "2080", False, False, False),
            ("5000", AccountRelationship.TargetKind.DIRECT_EXPENSE, "PROJECT_SITE_COST_CODE", "2080", True, False, False),
            ("1020", AccountRelationship.TargetKind.BANK_ACCOUNT, "BANK_REF", "2010", False, False, False),
            ("1010", AccountRelationship.TargetKind.CASH_ACCOUNT, "CASH_CUSTODIAN", "6010", False, False, False),
        ]:
            if acc_code in accounts:
                AccountRelationship.objects.get_or_create(
                    company=company,
                    account=accounts[acc_code],
                    target_kind=tkind,
                    defaults={
                        "extra_selector": xsel,
                        "suggested_counter_account": accounts.get(counter_code),
                        "require_project": req_prj,
                        "require_subledger": req_sub,
                        "require_reason_on_journal": req_rsn,
                    },
                )

        AccountingPolicy.objects.get_or_create(
            company=company,
            defaults={
                "inventory_method": AccountingPolicy.InventoryMethod.PERPETUAL,
                "revenue_recognition": AccountingPolicy.RevenueRecognition.CERTIFIED_RA_BILL,
                "default_retention_pct": Decimal("5.00"),
                "enforce_control_subledgers": True,
                "duplicate_invoice_check": True,
            },
        )

        # Posting Rules
        PostingRule.objects.get_or_create(
            company=company,
            voucher_type="MATERIAL_PURCHASE",
            rule_code="DEFAULT",
            defaults={
                "debit_account": accounts["1200"],
                "credit_account": accounts["2010"],
                "tax_account": accounts["1250"],
                "tds_account": accounts["2120"],
                "description": "Perpetual Material Purchase -> Inventory A/C + Input VAT",
            },
        )
        PostingRule.objects.get_or_create(
            company=company,
            voucher_type="SUBCONTRACTOR_BILL",
            rule_code="DEFAULT",
            defaults={
                "debit_account": accounts["5040"],
                "credit_account": accounts["2020"],
                "tds_account": accounts["2120"],
                "retention_account": accounts["2200"],
                "advance_account": accounts["1150"],
                "description": "Subcontractor RA Bill with Retention Payable & Sec 89 TDS",
            },
        )
        PostingRule.objects.get_or_create(
            company=company,
            voucher_type="CLIENT_RA_BILL",
            rule_code="DEFAULT",
            defaults={
                "debit_account": accounts["1100"],
                "credit_account": accounts["4010"],
                "tax_account": accounts["2110"],
                "retention_account": accounts["1160"],
                "advance_account": accounts["2070"],
                "description": "Certified Client RA Bill with Output VAT & Retention Receivable",
            },
        )

        # Construction Job Costing Masters & Subledger Parties
        dept_const, _ = Department.objects.get_or_create(company=company, code="CONST", defaults={"name": "Civil & Infrastructure Construction"})
        dept_fin, _ = Department.objects.get_or_create(company=company, code="FIN-HO", defaults={"name": "Head Office Finance & Admin"})
        CostCenter.objects.get_or_create(company=company, code="CC-STRUCT", defaults={"project": prj1, "name": "Structural & Foundation Cost Center"})
        wp1, _ = WorkPackage.objects.get_or_create(project=prj1, code="WP-SUB", defaults={"name": "Substructure & Piling Works", "budget_amount": Decimal("4500000.00")})
        boq1, _ = BoqItem.objects.get_or_create(
            project=prj1,
            code="BOQ-01",
            defaults={
                "company": company,
                "work_package": wp1,
                "cost_code": cc_mat,
                "description": "M35 Reinforced Pile Cap Concrete",
                "unit": "Cum",
                "boq_quantity": Decimal("450.000"),
                "unit_rate": Decimal("12500.00"),
                "budget_amount": Decimal("5625000.00"),
            },
        )
        EquipmentAsset.objects.get_or_create(
            company=company,
            code="EQ-CAT320",
            defaults={"name": "Caterpillar 320D Excavator", "asset_category": "Excavator", "hourly_rate": Decimal("4500.00"), "linked_asset_account": accounts["1510"]},
        )

        party_sup, _ = Party.objects.get_or_create(
            company=company,
            code="SUP-PANCH",
            defaults={"party_type": Party.PartyType.SUPPLIER, "name": "Panchakanya Steel & Cement Co.", "pan_vat_no": "601234567", "control_account": accounts["2010"], "project": prj1},
        )
        party_sub, _ = Party.objects.get_or_create(
            company=company,
            code="SUB-GORKHA",
            defaults={"party_type": Party.PartyType.SUBCONTRACTOR, "name": "Gorkha Civil Builders JV", "pan_vat_no": "605544332", "control_account": accounts["2020"], "project": prj1},
        )
        party_cli, _ = Party.objects.get_or_create(
            company=company,
            code="CLI-DOR",
            defaults={"party_type": Party.PartyType.CUSTOMER, "name": "Department of Roads, Nepal", "pan_vat_no": "300112233", "credit_limit": Decimal("25000000.00"), "control_account": accounts["1100"], "project": prj1},
        )

        # Employee Subledgers, Payroll Liabilities, Staff Advances & Staff Loans
        emp_specs = [
            ("EMP-1001", "Ram Sharma", "Site Engineer", dept_const, Decimal("65000.00"), Decimal("80000.00"), Decimal("30000.00"), Decimal("10000.00")),
            ("EMP-1002", "Sita Rai", "Senior Site Accountant", dept_fin, Decimal("55000.00"), Decimal("55000.00"), Decimal("15000.00"), Decimal("0.00")),
            ("EMP-1003", "Hari Thapa", "Site Foreman", dept_const, Decimal("42000.00"), Decimal("42000.00"), Decimal("20000.00"), Decimal("0.00")),
        ]
        for ecode, ename, desig, dept_obj, salary, unpaid_w, adv_orig, adv_adj in emp_specs:
            ep, _ = Party.objects.get_or_create(
                company=company,
                code=ecode,
                defaults={
                    "party_type": Party.PartyType.EMPLOYEE,
                    "name": ename,
                    "control_account": accounts.get("2035"),
                    "project": prj1,
                },
            )
            emp_prof, _ = EmployeeProfile.objects.get_or_create(
                company=company,
                employee_code=ecode,
                defaults={
                    "party": ep,
                    "full_name": ename,
                    "department": dept_obj,
                    "designation": desig,
                    "project": prj1,
                    "basic_salary": salary,
                },
            )
            PayrollLiability.objects.get_or_create(
                company=company,
                payroll_ref=f"PAY-2083-08-{ecode}",
                employee=emp_prof,
                defaults={
                    "project": prj1,
                    "period_label": "Mangsir 2083",
                    "control_account": accounts["2035"],
                    "gross_wages": unpaid_w,
                },
            )
            AdvanceRecord.objects.get_or_create(
                company=company,
                advance_no=f"ADV-2083-{ecode}",
                defaults={
                    "advance_type": AdvanceRecord.AdvanceType.EMPLOYEE_ADVANCE,
                    "party": ep,
                    "employee": emp_prof,
                    "project": prj1,
                    "control_account": accounts["1170"],
                    "issue_date": date(2026, 11, 10),
                    "bs_date": "2083-07-24",
                    "original_amount": adv_orig,
                    "adjusted_amount": adv_adj,
                    "status": AdvanceRecord.Status.PARTIALLY_ADJUSTED if adv_adj > 0 else AdvanceRecord.Status.OPEN,
                    "remarks": f"Site/travel expense advance issued to {ename}",
                },
            )
            if ecode == "EMP-1001":
                StaffLoan.objects.get_or_create(
                    company=company,
                    loan_no="SLN-2083-001",
                    defaults={
                        "employee": emp_prof,
                        "control_account": accounts["1175"],
                        "disbursement_date": date(2026, 10, 1),
                        "principal_amount": Decimal("120000.00"),
                        "repaid_amount": Decimal("20000.00"),
                        "interest_rate_pct": Decimal("6.00"),
                        "monthly_installment": Decimal("10000.00"),
                        "remaining_installments": 10,
                    },
                )

        # Sample Supplier Mobilization Advance for Subcontractor Adjustment testing
        AdvanceRecord.objects.get_or_create(
            company=company,
            advance_no="MOB-2083-SUB01",
            defaults={
                "advance_type": AdvanceRecord.AdvanceType.MOBILIZATION_ADVANCE,
                "party": party_sub,
                "project": prj1,
                "control_account": accounts["1150"],
                "issue_date": date(2026, 11, 5),
                "bs_date": "2083-07-19",
                "original_amount": Decimal("200000.00"),
                "adjusted_amount": Decimal("50000.00"),
                "status": AdvanceRecord.Status.PARTIALLY_ADJUSTED,
                "remarks": "Mobilization advance against Highway Substructure package",
            },
        )

        # Voucher UI Themes
        for tcode, tname, accent, vtype, is_def in [
            ("TALLY_CLASSIC", "Tally Classic Accounting Grid", "#0f766e", "ALL", True),
            ("ENTERPRISE_MODERN", "Enterprise Modern Cards", "#0284c7", "SALES", False),
            ("CONSTRUCTION_SITE", "Construction Site Operational", "#d97706", "SITE_PURCHASE", False),
            ("CONTRACTOR_JOBWORK", "Contractor & BOQ Billing", "#7c3aed", "SUBCONTRACTOR_BILL", False),
            ("MATERIAL_INVENTORY", "Material & Inventory Receipt", "#059669", "MATERIAL_PURCHASE", False),
            ("BANKING_TREASURY", "Banking & Cheque Instruments", "#1d4ed8", "PAYMENT", False),
            ("COMPACT_ENTRY", "Compact Fast Data Entry", "#334155", "JOURNAL", False),
            ("FORMAL_PRINT", "Formal A4 Print Mirror", "#0f172a", "CLIENT_RA_BILL", False),
        ]:
            VoucherThemeConfig.objects.get_or_create(
                company=company,
                voucher_type=vtype,
                theme_code=tcode,
                defaults={"name": tname, "accent_color": accent, "is_default": is_def},
            )

        # Sample Construction Vouchers (Subcontractor RA Bill + Perpetual Material Purchase)
        if not Voucher.objects.filter(company=company, idempotency_key="seed-sub-ra-1").exists():
            sc_v = VoucherService.create_draft(
                company=company,
                user=created_users["accountant"][0],
                data={
                    "voucher_type": Voucher.VoucherType.SUBCONTRACTOR_BILL,
                    "voucher_date": date(2026, 11, 21),
                    "branch": ho_branch,
                    "project": prj1,
                    "party": party_sub,
                    "supplier_invoice_no": "SC-RA-2083-01",
                    "narration": "Subcontractor Certified RA Bill #01 (5% Retention, 1.5% Sec 89 TDS)",
                    "gross_amount": Decimal("500000.00"),
                    "retention_amount": Decimal("25000.00"),
                    "tds_amount": Decimal("7500.00"),
                    "net_amount": Decimal("467500.00"),
                    "theme_code": "CONTRACTOR_JOBWORK",
                    "idempotency_key": "seed-sub-ra-1",
                    "scenario": {"taxable_amount": "500000.00", "vat_rate": "0", "retention_pct": "5.00", "tds_rate": "1.50"},
                },
                lines_data=[],
            )
            VoucherService.submit_voucher(voucher=sc_v, user=created_users["accountant"][0])
            ApprovalService.approve_voucher(voucher=sc_v, user=created_users["finance"][0])
            PostingService.post_voucher(voucher=sc_v, user=created_users["finance"][0])

        if not OperationalDocument.objects.filter(company=company, doc_number="GRN-2083-00001").exists():
            site_a = prj1.sites.first()
            grn = ConstructionOpsService.create_document(
                company=company,
                user=created_users["supervisor"][0],
                data={
                    "doc_kind": OperationalDocument.DocKind.GOODS_RECEIPT_NOTE,
                    "doc_number": "GRN-2083-00001",
                    "doc_date": date(2026, 11, 24),
                    "branch": ho_branch,
                    "project": prj1,
                    "site": site_a,
                    "party": party_sup,
                    "remarks": "Delivered 500 bags OPC Cement to Site A Store (no GL until billed).",
                },
                lines_data=[
                    {"item_code": "CEM-OPC53", "item_name": "OPC 53 Grade Cement", "unit": "Bags", "quantity": Decimal("500.000"), "unit_rate": Decimal("720.00"), "boq_item": boq1, "cost_code": cc_mat},
                ],
            )
            ConstructionOpsService.approve_document(doc=grn, user=created_users["finance"][0])

        # --- Phase 3 & Phase 4 ERP Seed (Budgeting, Inventory, Procurement, HR & Payroll) ---
        from apps.budgeting.models import Budget, BudgetLine
        from apps.budgeting.services import BudgetControlService
        from apps.inventory.models import GoodsReceiptNote, ItemCategory, ItemMaster, UnitOfMeasure, Warehouse
        from apps.inventory.services import InventoryService
        from apps.procurement.models import PurchaseOrder, RFQ, VendorProfile
        from apps.procurement.services import ProcurementService
        from apps.hr.models import Designation, EmployeeDetail, PayrollStatutoryRuleSet, SalaryStructure, WorkShift
        from apps.hr.services import HrService
        from datetime import time

        # 1. Budgets & Commitments Baseline
        bud = Budget.objects.filter(company=company, budget_code="BUD-2083-PRJ1").first()
        if not bud:
            bud = BudgetControlService.create_budget(
                company=company,
                user=created_users["finance"][0],
                data={
                    "budget_code": "BUD-2083-PRJ1",
                    "title": f"{prj1.name} FY 2083/84 Baseline Budget",
                    "budget_type": Budget.BudgetType.PROJECT,
                    "fiscal_year": fy,
                    "branch": ho_branch,
                    "project": prj1,
                    "notes": "Approved construction baseline covering Materials, Labor, Equipment, Subcontract & Overheads.",
                },
                lines_data=[
                    {"cost_category": "MATERIAL", "cost_code": cc_mat, "boq_item": boq1, "description": "Structural Cement & Rebar", "approved_amount": Decimal("4000000.00")},
                    {"cost_category": "LABOR", "cost_code": cc_lab, "description": "Site Engineers & Direct Workforce", "approved_amount": Decimal("2000000.00")},
                    {"cost_category": "SUBCONTRACT", "description": "Civil Subcontractor Works", "approved_amount": Decimal("2500000.00")},
                    {"cost_category": "OVERHEAD", "description": "Site Administration & Transport", "approved_amount": Decimal("1000000.00")},
                ],
            )
            BudgetControlService.approve_budget(budget=bud, user=created_users["admin"][0])
        mat_bline = bud.versions.first().lines.filter(cost_category="MATERIAL").first() if bud.versions.exists() else None

        # 2. Inventory Masters & Warehouses
        cat_cem, _ = ItemCategory.objects.get_or_create(company=company, code="CEM", defaults={"name": "Cement & Binders"})
        cat_stl, _ = ItemCategory.objects.get_or_create(company=company, code="STL", defaults={"name": "Reinforcement Steel"})
        u_bag, _ = UnitOfMeasure.objects.get_or_create(company=company, code="Bags", defaults={"name": "50 Kg Bags"})
        u_mt, _ = UnitOfMeasure.objects.get_or_create(company=company, code="MT", defaults={"name": "Metric Ton"})

        item_cem, _ = ItemMaster.objects.get_or_create(
            company=company, item_code="CEM-OPC53",
            defaults={
                "name": "OPC 53 Grade Cement", "category": cat_cem, "brand": "Shivam",
                "primary_unit": u_bag, "reorder_level": Decimal("200.000"),
                "standard_rate": Decimal("720.00"), "last_purchase_rate": Decimal("720.00"),
                "valuation_method": ItemMaster.ValuationMethod.FIFO,
                "inventory_account": accounts["1200"], "expense_wip_account": accounts["1400"],
            },
        )
        item_stl, _ = ItemMaster.objects.get_or_create(
            company=company, item_code="STL-TMT16",
            defaults={
                "name": "16mm Fe500D TMT Rebar", "category": cat_stl, "brand": "Panchakanya",
                "primary_unit": u_mt, "reorder_level": Decimal("5.000"),
                "standard_rate": Decimal("108000.00"), "last_purchase_rate": Decimal("108000.00"),
                "valuation_method": ItemMaster.ValuationMethod.WEIGHTED_AVG,
                "inventory_account": accounts["1200"], "expense_wip_account": accounts["1400"],
            },
        )
        wh_ho, _ = Warehouse.objects.get_or_create(company=company, code="WH-HO", defaults={"name": "Kathmandu Central Store", "store_kind": Warehouse.StoreKind.CENTRAL, "branch": ho_branch})
        wh_site, _ = Warehouse.objects.get_or_create(company=company, code="WH-SITE-A", defaults={"name": "Highway Site A Store", "store_kind": Warehouse.StoreKind.SITE_STORE, "project": prj1, "site": prj1.sites.first()})

        # 3. Procurement Vendors, PR, RFQ, Quotations, Approved PO, GRN & Issue
        vp_sup, _ = VendorProfile.objects.get_or_create(
            company=company, party=party_sup,
            defaults={"vendor_category": VendorProfile.Category.MATERIALS, "pan_vat_no": "601234567", "bank_name": "Nabil Bank", "bank_account_no": "0010100044221", "status": VendorProfile.Status.APPROVED},
        )
        vp_sub, _ = VendorProfile.objects.get_or_create(
            company=company, party=party_sub,
            defaults={"vendor_category": VendorProfile.Category.CONTRACTOR, "pan_vat_no": "605544332", "bank_name": "Global IME Bank", "bank_account_no": "0120100088991", "status": VendorProfile.Status.APPROVED},
        )
        if not PurchaseOrder.objects.filter(company=company, po_number="PO-2083-0001").exists():
            pr = ProcurementService.create_requisition(
                company=company, user=created_users["supervisor"][0],
                data={"requisition_no": "PR-2083-0001", "requisition_date": date(2026, 11, 20), "required_delivery_date": date(2026, 11, 25), "department": dept_const, "project": prj1, "site": prj1.sites.first(), "priority": "HIGH"},
                lines_data=[{"item": item_cem, "description": "OPC 53 Cement for Pile Caps", "unit": "Bags", "requested_qty": Decimal("500.000"), "estimated_rate": Decimal("720.00"), "cost_code": cc_mat, "budget_line": mat_bline}],
            )
            ProcurementService.approve_requisition(requisition=pr, user=created_users["finance"][0])
            rfq = RFQ.objects.create(company=company, rfq_no="RFQ-2083-0001", rfq_date=date(2026, 11, 21), deadline=date(2026, 11, 23), requisition=pr, created_by=created_users["accountant"][0])
            rfq.invited_vendors.set([vp_sup, vp_sub])
            ProcurementService.submit_quotation(
                company=company, rfq=rfq, vendor=vp_sup,
                data={"quotation_ref": "QT-PS-91", "quoted_date": date(2026, 11, 22), "delivery_days": 3, "freight_charge": Decimal("4000.00"), "tax_amount": Decimal("46800.00")},
                lines_data=[{"item": item_cem, "description": "OPC 53 Cement", "quantity": Decimal("500.000"), "unit_rate": Decimal("720.00")}],
            )
            ProcurementService.submit_quotation(
                company=company, rfq=rfq, vendor=vp_sub,
                data={"quotation_ref": "QT-GK-18", "quoted_date": date(2026, 11, 22), "delivery_days": 6, "freight_charge": Decimal("9000.00"), "tax_amount": Decimal("47450.00")},
                lines_data=[{"item": item_cem, "description": "OPC 53 Cement", "quantity": Decimal("500.000"), "unit_rate": Decimal("730.00")}],
            )
            ProcurementService.select_quotation(company=company, rfq=rfq, recommended_vendor=vp_sup, justification="Lowest total landed cost & fastest 3-day site delivery", user=created_users["finance"][0])
            po = ProcurementService.create_purchase_order(
                company=company, user=created_users["accountant"][0],
                data={"po_number": "PO-2083-0001", "po_date": date(2026, 11, 23), "vendor": vp_sup, "requisition": pr, "rfq": rfq, "project": prj1, "site": prj1.sites.first(), "justification": "Awarded lowest landed cost vendor"},
                lines_data=[{"item": item_cem, "description": "OPC 53 Grade Cement", "unit": "Bags", "ordered_qty": Decimal("500.000"), "unit_rate": Decimal("720.00"), "tax_rate": Decimal("13.00"), "cost_code": cc_mat, "budget_line": mat_bline}],
            )
            ProcurementService.approve_purchase_order(po=po, user=created_users["finance"][0])
            grn_inv = InventoryService.create_and_approve_grn(
                company=company, user=created_users["supervisor"][0],
                data={"grn_number": "GRN-INV-2083-01", "grn_date": date(2026, 11, 24), "purchase_order": po, "vendor": party_sup, "warehouse": wh_site, "project": prj1, "site": prj1.sites.first(), "challan_no": "CH-7712"},
                lines_data=[{"po_line": po.lines.first(), "item": item_cem, "received_qty": Decimal("500.000"), "accepted_qty": Decimal("500.000"), "unit_rate": Decimal("720.00"), "batch_no": "BATCH-OPC-01"}],
                auto_approve=True,
            )
            InventoryService.create_and_approve_issue(
                company=company, user=created_users["supervisor"][0],
                data={"issue_no": "ISS-2083-0001", "issue_date": date(2026, 11, 25), "warehouse": wh_site, "project": prj1, "site": prj1.sites.first(), "receiver_name": "Hari Thapa"},
                lines_data=[{"item": item_cem, "quantity": Decimal("150.000"), "cost_code": cc_mat, "boq_item": boq1}],
                auto_approve=True,
            )

        # 4. HR Shifts, Extended Details, Nepal FY 2083/84 Statutory Rules, Attendance & Timesheet
        des_eng, _ = Designation.objects.get_or_create(company=company, code="ENG", defaults={"title": "Site Engineer"})
        shift_day, _ = WorkShift.objects.get_or_create(company=company, name="Standard Day Shift", defaults={"start_time": time(9, 0), "end_time": time(17, 0), "standard_hours": Decimal("8.00"), "overtime_multiplier": Decimal("1.50")})
        PayrollStatutoryRuleSet.objects.get_or_create(
            company=company,
            rule_name="Nepal FY 2083/84 Standard PF/Tax Slabs",
            effective_from=date(2026, 7, 16),
            defaults={
                "employee_pf_pct": Decimal("10.00"), "employer_pf_pct": Decimal("10.00"),
                "employee_ssf_pct": Decimal("11.00"), "employer_ssf_pct": Decimal("20.00"),
                "tax_slabs_single": [
                    {"upto": 500000, "rate": 1}, {"upto": 700000, "rate": 10}, {"upto": 1000000, "rate": 20}, {"upto": 2000000, "rate": 30}, {"upto": None, "rate": 36},
                ],
                "tax_slabs_couple": [
                    {"upto": 600000, "rate": 1}, {"upto": 800000, "rate": 10}, {"upto": 1100000, "rate": 20}, {"upto": 2000000, "rate": 30}, {"upto": None, "rate": 36},
                ],
            },
        )
        for emp_prof in EmployeeProfile.objects.filter(company=company):
            EmployeeDetail.objects.get_or_create(
                company=company, employee_profile=emp_prof,
                defaults={"designation_obj": des_eng, "shift": shift_day, "pf_enrolled": True, "hourly_rate": Decimal("320.00")},
            )
            SalaryStructure.objects.get_or_create(
                company=company, employee=emp_prof, is_current=True,
                defaults={"effective_from": date(2026, 7, 16), "basic_salary": emp_prof.basic_salary, "site_allowance": Decimal("5000.00")},
            )
        ram = EmployeeProfile.objects.filter(company=company, employee_code="EMP-1001").first()
        if ram:
            HrService.upsert_attendance(
                company=company, user=created_users["supervisor"][0],
                data={"employee": ram, "project": prj1, "attendance_date": date(2026, 11, 29), "overtime_hours": Decimal("2.00"), "status": "PRESENT"},
            )

        # 5. Sundry Debtors & Sundry Creditors Management Hub (Groups, Customer Profiles, OpenItems, Collection & PayPlan)
        from apps.party_hub.models import CollectionActivity, CustomerProfile, OpenItem, PartyGroup, PaymentProposal, PartyReconciliationRun
        from apps.party_hub.services import OpenItemSyncService, PayableService, PartyReconciliationService, ReceivableService

        grp_govt, _ = PartyGroup.objects.get_or_create(
            company=company, hub_scope=PartyGroup.HubScope.DEBTOR, code="GOVT-INFRA",
            defaults={"name": "Government & Infrastructure Clients", "default_control_account": accounts["1100"], "default_payment_terms_days": 45},
        )
        PartyGroup.objects.get_or_create(
            company=company, hub_scope=PartyGroup.HubScope.CREDITOR, code="MAT-SUP",
            defaults={"name": "Cement & Steel Suppliers", "default_control_account": accounts["2010"], "default_payment_terms_days": 30},
        )
        PartyGroup.objects.get_or_create(
            company=company, hub_scope=PartyGroup.HubScope.CREDITOR, code="CIV-SUB",
            defaults={"name": "Civil & Structural Subcontractors", "default_control_account": accounts["2020"], "default_payment_terms_days": 30},
        )
        for cust_p in Party.objects.filter(company=company, party_type=Party.PartyType.CUSTOMER):
            CustomerProfile.objects.get_or_create(
                company=company,
                party=cust_p,
                defaults={
                    "group": grp_govt,
                    "customer_category": CustomerProfile.Category.GOVERNMENT,
                    "pan_vat_no": cust_p.pan_vat_no or "201998877",
                    "contract_number": f"CON-2083-{cust_p.code}",
                    "contract_value": Decimal("45000000.00"),
                    "credit_days": cust_p.payment_terms_days or 45,
                    "approval_status": CustomerProfile.ApprovalStatus.APPROVED,
                    "approved_by": created_users["finance"][0],
                },
            )
        if not CustomerProfile.objects.filter(company=company, party__code="CLI-METRO").exists():
            ReceivableService.register_customer(
                company=company,
                user=created_users["finance"][0],
                party_data={"code": "CLI-METRO", "name": "Kathmandu Valley Metro Infrastructure Ltd.", "pan_vat_no": "309887766", "phone": "+977-1-5520101", "email": "billing@kvmetro.com.np", "credit_limit": Decimal("25000000.00"), "payment_terms_days": 30, "project": prj1},
                profile_data={"group": grp_govt, "customer_category": CustomerProfile.Category.CORPORATE, "pan_vat_no": "309887766", "contract_number": "KVM-2083-09", "contract_value": Decimal("18500000.00")},
            )
        # Synchronize Phase-1 opening balances & legacy vouchers with Party Subledgers so GL == Subledger 100%
        from apps.accounting.models import LedgerEntry, PartyLedgerEntry

        Party.objects.filter(company=company, code="CLI-DOR").update(opening_debit=accounts["1100"].opening_debit)
        Party.objects.filter(company=company, code="SUP-PANCH").update(opening_credit=accounts["2010"].opening_credit)
        if accounts.get("2200") and accounts["2200"].opening_credit > 0:
            Party.objects.get_or_create(
                company=company,
                code="SUB-OPEN-RET",
                defaults={
                    "party_type": Party.PartyType.SUBCONTRACTOR,
                    "name": "Legacy Subcontractor Retention Reserve",
                    "control_account": accounts["2200"],
                    "opening_credit": accounts["2200"].opening_credit,
                    "project": prj1,
                },
            )
        cli_dor = Party.objects.filter(company=company, code="CLI-DOR").first()
        sup_panch = Party.objects.filter(company=company, code="SUP-PANCH").first()
        for acc_obj, def_party, ekind in [
            (accounts["1100"], cli_dor, PartyLedgerEntry.EntryKind.INVOICE),
            (accounts["2010"], sup_panch, PartyLedgerEntry.EntryKind.INVOICE),
        ]:
            if not def_party:
                continue
            for le in LedgerEntry.objects.select_related("voucher").filter(company=company, account=acc_obj, party__isnull=True):
                LedgerEntry.objects.filter(pk=le.pk).update(party=def_party)
                if not PartyLedgerEntry.objects.filter(company=company, voucher=le.voucher, control_account=acc_obj).exists():
                    PartyLedgerEntry.objects.create(
                        company=company,
                        party=def_party,
                        control_account=acc_obj,
                        voucher=le.voucher,
                        project=le.project or prj1,
                        entry_date=le.posting_date,
                        bs_date=le.bs_date,
                        due_date=le.voucher.due_date or (le.posting_date + timedelta(days=30)),
                        entry_kind=ekind,
                        reference_no=le.voucher.reference_no or le.voucher.voucher_no or "",
                        debit=le.base_debit,
                        credit=le.base_credit,
                        narration=le.narration or le.voucher.narration[:255],
                    )

        # Synchronize OpenItem & Retention rows for all posted vouchers idempotently
        for pv in Voucher.objects.filter(company=company, status=Voucher.Status.POSTED).order_by("voucher_date"):
            OpenItemSyncService.sync_voucher_open_items(voucher=pv)

        # Ensure sample RA billing, collection follow-up, payment proposal & clean reconciliation
        cli_metro = Party.objects.filter(company=company, code="CLI-METRO").first()
        if cli_metro and not OpenItem.objects.filter(company=company, party=cli_metro, is_unallocated_credit=False).exists():
            ReceivableService.create_and_post_invoice_or_bill(
                company=company,
                user=created_users["finance"][0],
                party=cli_metro,
                voucher_type=Voucher.VoucherType.CLIENT_RA_BILL,
                invoice_date=date(2026, 11, 5),
                due_date=date(2026, 11, 20),
                gross_amount=Decimal("1000000.00"),
                vat_rate=Decimal("13.00"),
                retention_pct=Decimal("5.00"),
                advance_recovery_amount=Decimal("50000.00"),
                project=prj1,
                reference_no="RA-KVM-002",
                narration="Client Running Account Bill #2 — Foundation & Piling",
            )
        first_ar = OpenItem.objects.filter(company=company, hub_side=OpenItem.HubSide.RECEIVABLE, is_unallocated_credit=False).first()
        if first_ar and not CollectionActivity.objects.filter(company=company, open_item=first_ar).exists():
            CollectionActivity.objects.create(
                company=company,
                party=first_ar.party,
                open_item=first_ar,
                assigned_to=created_users["finance"][0],
                activity_type=CollectionActivity.ActivityType.CALL,
                contacted_at=date(2026, 11, 26),
                promised_amount=first_ar.remaining_amount,
                promised_date=date(2026, 12, 5),
                next_followup_date=date(2026, 12, 6),
                outcome="Client confirmed IPC certification cleared; cheque processing.",
                status=CollectionActivity.Status.PROMISED,
                created_by=created_users["accountant"][0],
            )
        bank_acc = BankAccount.objects.filter(company=company, status=BankAccount.Status.ACTIVE).first()
        first_ap = OpenItem.objects.filter(company=company, hub_side=OpenItem.HubSide.PAYABLE, is_unallocated_credit=False).exclude(status=OpenItem.Status.SETTLED).first()
        if bank_acc and first_ap and not PaymentProposal.objects.filter(company=company).exists():
            PayableService.create_payment_proposal(
                company=company,
                user=created_users["accountant"][0],
                proposal_date=date(2026, 11, 28),
                bank_account=bank_acc,
                items=[{"open_item_id": str(first_ap.id), "proposed_amount": str(min(first_ap.remaining_amount, Decimal("50000.00"))), "priority": "HIGH", "remarks": "Priority site material settlement"}],
                project=prj1,
                notes="Weekly AP liquidity schedule",
            )
        if not PartyReconciliationRun.objects.filter(company=company).exists():
            PartyReconciliationService.run_reconciliation(company=company, user=created_users["finance"][0], as_of_date=date(2026, 11, 29))

        TallyConfigService.ensure_default_voucher_catalog(company)

        self.stdout.write(self.style.SUCCESS("Seeded Maya OS demo data for HIPL (FY 2083/84)."))

