"""
Complete IFRS-Compliant Chart of Accounts Seed Script
Implements the full 5-element structure per IAS 1:
  Assets | Liabilities | Equity | Revenue | Expenses

Key IFRS standards covered:
  IAS 1  – Presentation | IAS 7 – Cash Flows | IAS 12 – Tax
  IAS 16 – PPE         | IAS 36 – Impairment | IAS 37 – Provisions
  IAS 38 – Intangibles | IAS 40 – Investment Property
  IFRS 9 – Financial Instruments (ECL) | IFRS 15 – Revenue
  IFRS 16 – Leases

App-required codes: 1111 Cash in Hand, 1112 Petty Cash, 1113 CC Clearing,
  1114 Undeposited Funds, A2.1 reporting tag on PPE
"""

import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app.core.database import SessionLocal
from app.models.accounting import AccountingCode
import uuid

# Valid categories per type (from model validator):
# Asset:     Current Asset | Fixed Asset | Inventory | Trade Receivables |
#            Cash | Bank | Prepaid Expenses | Investments |
#            Intangible Assets | Accumulated Depreciation
# Liability: Current Liability | Long-Term Liability | Trade Payables |
#            Accrued Liabilities | VAT Payable | Tax Payable |
#            Loans Payable | Deferred Revenue | Notes Payable
# Equity:    Equity Capital | Retained Earnings | Opening Balance Equity |
#            Owner Equity | Common Stock | Dividends | Drawings
# Revenue:   Sales Revenue | Service Revenue | Other Revenue |
#            Operating Revenue | Interest Income | Rental Income |
#            Dividend Income | Gain on Sale of Assets
# Expense:   Operating Expense | Depreciation | Cost of Sales |
#            Tax Expense | Salaries and Wages | Rent Expense | Utilities |
#            Insurance | Office Supplies | Marketing | Professional Fees |
#            Interest Expense | Repairs and Maintenance | Travel Expense |
#            Bad Debts

ACCOUNTS = [
    # ══════════════════════════════════════════════════════════
    # ASSETS  1xxx
    # ══════════════════════════════════════════════════════════
    {"code": "1000", "name": "Assets",                              "type": "Asset",     "category": "Current Asset",     "is_parent": True},

    # ── Current Assets ──────────────────────────────────────
    {"code": "1100", "name": "Current Assets",                      "type": "Asset",     "category": "Current Asset",     "is_parent": True, "parent": "1000"},

    # Cash & Equivalents (IAS 7)
    {"code": "1110", "name": "Cash and Cash Equivalents",           "type": "Asset",     "category": "Cash",              "is_parent": True, "parent": "1100"},
    {"code": "1111", "name": "Cash in Hand",                        "type": "Asset",     "category": "Cash",              "parent": "1110"},
    {"code": "1112", "name": "Petty Cash",                          "type": "Asset",     "category": "Cash",              "parent": "1110"},
    {"code": "1113", "name": "Credit Card Clearing",                "type": "Asset",     "category": "Cash",              "parent": "1110"},
    {"code": "1114", "name": "Undeposited Funds",                   "type": "Asset",     "category": "Cash",              "parent": "1110"},

    # Bank Accounts
    {"code": "1120", "name": "Bank Accounts",                       "type": "Asset",     "category": "Bank",              "is_parent": True, "parent": "1100"},
    {"code": "1121", "name": "Main Bank Account",                   "type": "Asset",     "category": "Bank",              "parent": "1120"},
    {"code": "1122", "name": "Savings Account",                     "type": "Asset",     "category": "Bank",              "parent": "1120"},
    {"code": "1123", "name": "Business Cheque Account",             "type": "Asset",     "category": "Bank",              "parent": "1120"},
    {"code": "1124", "name": "Foreign Currency Account",            "type": "Asset",     "category": "Bank",              "parent": "1120"},

    # Trade Receivables (IFRS 9 – ECL)
    {"code": "1130", "name": "Trade and Other Receivables",         "type": "Asset",     "category": "Trade Receivables", "is_parent": True, "parent": "1100"},
    {"code": "1131", "name": "Accounts Receivable - Trade",         "type": "Asset",     "category": "Trade Receivables", "parent": "1130"},
    {"code": "1132", "name": "Allowance for Doubtful Debts",        "type": "Asset",     "category": "Trade Receivables", "parent": "1130"},
    {"code": "1133", "name": "Notes Receivable",                    "type": "Asset",     "category": "Trade Receivables", "parent": "1130"},
    {"code": "1134", "name": "Staff Loans Receivable",              "type": "Asset",     "category": "Trade Receivables", "parent": "1130"},
    {"code": "1135", "name": "Intercompany Receivables",            "type": "Asset",     "category": "Trade Receivables", "parent": "1130"},

    # Inventories (IAS 2)
    {"code": "1140", "name": "Inventories",                         "type": "Asset",     "category": "Inventory",         "is_parent": True, "parent": "1100"},
    {"code": "1141", "name": "Raw Materials",                       "type": "Asset",     "category": "Inventory",         "parent": "1140"},
    {"code": "1142", "name": "Work in Progress",                    "type": "Asset",     "category": "Inventory",         "parent": "1140"},
    {"code": "1143", "name": "Finished Goods",                      "type": "Asset",     "category": "Inventory",         "parent": "1140"},
    {"code": "1144", "name": "Merchandise Inventory",               "type": "Asset",     "category": "Inventory",         "parent": "1140"},
    {"code": "1145", "name": "Goods in Transit",                    "type": "Asset",     "category": "Inventory",         "parent": "1140"},
    {"code": "1146", "name": "Inventory Write-down Provision",      "type": "Asset",     "category": "Inventory",         "parent": "1140"},

    # Prepayments & Other Current Assets
    {"code": "1150", "name": "Prepayments and Other Current Assets","type": "Asset",     "category": "Prepaid Expenses",  "is_parent": True, "parent": "1100"},
    {"code": "1151", "name": "Prepaid Expenses",                    "type": "Asset",     "category": "Prepaid Expenses",  "parent": "1150"},
    {"code": "1152", "name": "Advance Payments to Suppliers",       "type": "Asset",     "category": "Prepaid Expenses",  "parent": "1150"},
    {"code": "1153", "name": "Short-term Deposits",                 "type": "Asset",     "category": "Prepaid Expenses",  "parent": "1150"},
    {"code": "1154", "name": "Other Current Assets",                "type": "Asset",     "category": "Prepaid Expenses",  "parent": "1150"},

    # VAT & Tax Receivable
    {"code": "1160", "name": "VAT and Tax Receivable",              "type": "Asset",     "category": "Current Asset",     "is_parent": True, "parent": "1100"},
    {"code": "1161", "name": "Input VAT - Standard Rate",           "type": "Asset",     "category": "Current Asset",     "parent": "1160"},
    {"code": "1162", "name": "Input VAT - Zero Rate",               "type": "Asset",     "category": "Current Asset",     "parent": "1160"},
    {"code": "1163", "name": "Deferred VAT",                        "type": "Asset",     "category": "Current Asset",     "parent": "1160"},
    {"code": "1164", "name": "Corporate Tax Receivable",            "type": "Asset",     "category": "Current Asset",     "parent": "1160"},
    {"code": "1165", "name": "PAYE Receivable",                     "type": "Asset",     "category": "Current Asset",     "parent": "1160"},

    # ── Non-Current Assets ───────────────────────────────────
    {"code": "1200", "name": "Non-Current Assets",                  "type": "Asset",     "category": "Fixed Asset",       "is_parent": True, "parent": "1000"},

    # Property, Plant & Equipment – IAS 16
    {"code": "1210", "name": "Property, Plant and Equipment",       "type": "Asset",     "category": "Fixed Asset",       "is_parent": True, "parent": "1200", "reporting_tag": "A2.1"},
    {"code": "1211", "name": "Land",                                "type": "Asset",     "category": "Fixed Asset",       "parent": "1210"},
    {"code": "1212", "name": "Buildings",                           "type": "Asset",     "category": "Fixed Asset",       "parent": "1210"},
    {"code": "1213", "name": "Plant and Machinery",                 "type": "Asset",     "category": "Fixed Asset",       "parent": "1210"},
    {"code": "1214", "name": "Motor Vehicles",                      "type": "Asset",     "category": "Fixed Asset",       "parent": "1210"},
    {"code": "1215", "name": "Computer Equipment",                  "type": "Asset",     "category": "Fixed Asset",       "parent": "1210"},
    {"code": "1216", "name": "Office Furniture and Equipment",      "type": "Asset",     "category": "Fixed Asset",       "parent": "1210"},
    {"code": "1217", "name": "Leasehold Improvements",              "type": "Asset",     "category": "Fixed Asset",       "parent": "1210"},
    {"code": "1218", "name": "Capital Work in Progress",            "type": "Asset",     "category": "Fixed Asset",       "parent": "1210"},

    # Accumulated Depreciation – PPE (contra-asset)
    {"code": "1220", "name": "Accumulated Depreciation - PPE",      "type": "Asset",     "category": "Accumulated Depreciation", "is_parent": True, "parent": "1200"},
    {"code": "1221", "name": "Accum. Dep. - Buildings",             "type": "Asset",     "category": "Accumulated Depreciation", "parent": "1220"},
    {"code": "1222", "name": "Accum. Dep. - Plant and Machinery",   "type": "Asset",     "category": "Accumulated Depreciation", "parent": "1220"},
    {"code": "1223", "name": "Accum. Dep. - Motor Vehicles",        "type": "Asset",     "category": "Accumulated Depreciation", "parent": "1220"},
    {"code": "1224", "name": "Accum. Dep. - Computer Equipment",    "type": "Asset",     "category": "Accumulated Depreciation", "parent": "1220"},
    {"code": "1225", "name": "Accum. Dep. - Furniture & Equipment", "type": "Asset",     "category": "Accumulated Depreciation", "parent": "1220"},

    # Intangible Assets – IAS 38
    {"code": "1230", "name": "Intangible Assets",                   "type": "Asset",     "category": "Intangible Assets", "is_parent": True, "parent": "1200"},
    {"code": "1231", "name": "Goodwill",                            "type": "Asset",     "category": "Intangible Assets", "parent": "1230"},
    {"code": "1232", "name": "Patents and Trademarks",              "type": "Asset",     "category": "Intangible Assets", "parent": "1230"},
    {"code": "1233", "name": "Computer Software and Licenses",      "type": "Asset",     "category": "Intangible Assets", "parent": "1230"},
    {"code": "1234", "name": "Accumulated Amortization",            "type": "Asset",     "category": "Accumulated Depreciation", "parent": "1230"},

    # Right-of-Use Assets – IFRS 16
    {"code": "1240", "name": "Right-of-Use Assets",                 "type": "Asset",     "category": "Fixed Asset",       "is_parent": True, "parent": "1200"},
    {"code": "1241", "name": "ROU Asset - Buildings",               "type": "Asset",     "category": "Fixed Asset",       "parent": "1240"},
    {"code": "1242", "name": "ROU Asset - Vehicles",                "type": "Asset",     "category": "Fixed Asset",       "parent": "1240"},
    {"code": "1243", "name": "Accum. Dep. - ROU Assets",            "type": "Asset",     "category": "Accumulated Depreciation", "parent": "1240"},

    # Long-term Investments & Other
    {"code": "1260", "name": "Long-term Investments and Other",     "type": "Asset",     "category": "Investments",       "is_parent": True, "parent": "1200"},
    {"code": "1261", "name": "Investment in Subsidiaries",          "type": "Asset",     "category": "Investments",       "parent": "1260"},
    {"code": "1262", "name": "Investment in Associates",            "type": "Asset",     "category": "Investments",       "parent": "1260"},
    {"code": "1263", "name": "Other Long-term Investments",         "type": "Asset",     "category": "Investments",       "parent": "1260"},
    {"code": "1264", "name": "Long-term Deposits",                  "type": "Asset",     "category": "Investments",       "parent": "1260"},
    {"code": "1265", "name": "Deferred Tax Asset",                  "type": "Asset",     "category": "Investments",       "parent": "1260"},

    # ══════════════════════════════════════════════════════════
    # LIABILITIES  2xxx
    # ══════════════════════════════════════════════════════════
    {"code": "2000", "name": "Liabilities",                         "type": "Liability", "category": "Current Liability", "is_parent": True},

    # ── Current Liabilities ──────────────────────────────────
    {"code": "2100", "name": "Current Liabilities",                 "type": "Liability", "category": "Current Liability", "is_parent": True, "parent": "2000"},

    # Trade Payables
    {"code": "2110", "name": "Trade and Other Payables",            "type": "Liability", "category": "Trade Payables",    "is_parent": True, "parent": "2100"},
    {"code": "2111", "name": "Accounts Payable - Trade Suppliers",  "type": "Liability", "category": "Trade Payables",    "parent": "2110"},
    {"code": "2112", "name": "Accrued Expenses",                    "type": "Liability", "category": "Accrued Liabilities","parent": "2110"},
    {"code": "2113", "name": "Goods Received Not Invoiced",         "type": "Liability", "category": "Trade Payables",    "parent": "2110"},
    {"code": "2114", "name": "Customer Deposits and Advances",      "type": "Liability", "category": "Deferred Revenue",  "parent": "2110"},

    # Short-term Borrowings
    {"code": "2120", "name": "Short-term Borrowings",               "type": "Liability", "category": "Loans Payable",     "is_parent": True, "parent": "2100"},
    {"code": "2121", "name": "Bank Overdraft",                      "type": "Liability", "category": "Loans Payable",     "parent": "2120"},
    {"code": "2122", "name": "Short-term Loans",                    "type": "Liability", "category": "Loans Payable",     "parent": "2120"},
    {"code": "2123", "name": "Current Portion of Long-term Debt",   "type": "Liability", "category": "Loans Payable",     "parent": "2120"},

    # Tax Liabilities
    {"code": "2130", "name": "Tax Liabilities",                     "type": "Liability", "category": "Tax Payable",       "is_parent": True, "parent": "2100"},
    {"code": "2131", "name": "VAT Control Account",                 "type": "Liability", "category": "VAT Payable",       "parent": "2130"},
    {"code": "2132", "name": "VAT Payable (Output VAT)",            "type": "Liability", "category": "VAT Payable",       "parent": "2130"},
    {"code": "2133", "name": "VAT Receivable Contra",               "type": "Liability", "category": "VAT Payable",       "parent": "2130"},
    {"code": "2134", "name": "PAYE Payable",                        "type": "Liability", "category": "Tax Payable",       "parent": "2130"},
    {"code": "2135", "name": "Corporate Tax Payable",               "type": "Liability", "category": "Tax Payable",       "parent": "2130"},
    {"code": "2136", "name": "Withholding Tax Payable",             "type": "Liability", "category": "Tax Payable",       "parent": "2130"},

    # Other Current Liabilities
    {"code": "2140", "name": "Other Current Liabilities",           "type": "Liability", "category": "Current Liability", "is_parent": True, "parent": "2100"},
    {"code": "2141", "name": "Deferred Revenue",                    "type": "Liability", "category": "Deferred Revenue",  "parent": "2140"},
    {"code": "2142", "name": "Dividends Payable",                   "type": "Liability", "category": "Current Liability", "parent": "2140"},
    {"code": "2143", "name": "Wages and Salaries Payable",          "type": "Liability", "category": "Accrued Liabilities","parent": "2140"},
    {"code": "2144", "name": "Intercompany Payables",               "type": "Liability", "category": "Current Liability", "parent": "2140"},

    # ── Non-Current Liabilities ──────────────────────────────
    {"code": "2200", "name": "Non-Current Liabilities",             "type": "Liability", "category": "Long-Term Liability","is_parent": True, "parent": "2000"},

    # Long-term Borrowings
    {"code": "2210", "name": "Long-term Borrowings",                "type": "Liability", "category": "Loans Payable",     "is_parent": True, "parent": "2200"},
    {"code": "2211", "name": "Long-term Bank Loans",                "type": "Liability", "category": "Loans Payable",     "parent": "2210"},
    {"code": "2212", "name": "Bonds Payable",                       "type": "Liability", "category": "Notes Payable",     "parent": "2210"},
    {"code": "2213", "name": "Mortgage Payable",                    "type": "Liability", "category": "Loans Payable",     "parent": "2210"},

    # Lease Liabilities – IFRS 16
    {"code": "2220", "name": "Lease Liabilities",                   "type": "Liability", "category": "Long-Term Liability","is_parent": True, "parent": "2200"},
    {"code": "2221", "name": "Lease Liability - Current Portion",   "type": "Liability", "category": "Current Liability", "parent": "2220"},
    {"code": "2222", "name": "Lease Liability - Non-Current",       "type": "Liability", "category": "Long-Term Liability","parent": "2220"},

    # Provisions – IAS 37
    {"code": "2230", "name": "Provisions",                          "type": "Liability", "category": "Long-Term Liability","is_parent": True, "parent": "2200"},
    {"code": "2231", "name": "Provision for Employee Benefits",     "type": "Liability", "category": "Long-Term Liability","parent": "2230"},
    {"code": "2232", "name": "Provision for Warranties",            "type": "Liability", "category": "Long-Term Liability","parent": "2230"},
    {"code": "2233", "name": "Provision for Legal Claims",          "type": "Liability", "category": "Long-Term Liability","parent": "2230"},
    {"code": "2234", "name": "Provision for Restructuring",         "type": "Liability", "category": "Long-Term Liability","parent": "2230"},

    # Deferred Tax – IAS 12
    {"code": "2240", "name": "Deferred Tax Liabilities",            "type": "Liability", "category": "Long-Term Liability","parent": "2200"},

    # ══════════════════════════════════════════════════════════
    # EQUITY  3xxx
    # ══════════════════════════════════════════════════════════
    {"code": "3000", "name": "Equity",                              "type": "Equity",    "category": "Equity Capital",    "is_parent": True},

    # Share Capital
    {"code": "3100", "name": "Share Capital",                       "type": "Equity",    "category": "Common Stock",      "is_parent": True, "parent": "3000"},
    {"code": "3110", "name": "Ordinary Share Capital",              "type": "Equity",    "category": "Common Stock",      "parent": "3100"},
    {"code": "3120", "name": "Share Premium",                       "type": "Equity",    "category": "Common Stock",      "parent": "3100"},

    # Retained Earnings
    {"code": "3200", "name": "Retained Earnings",                   "type": "Equity",    "category": "Retained Earnings", "is_parent": True, "parent": "3000"},
    {"code": "3210", "name": "Opening Retained Earnings",           "type": "Equity",    "category": "Opening Balance Equity","parent": "3200"},
    {"code": "3220", "name": "Current Year Profit / (Loss)",        "type": "Equity",    "category": "Retained Earnings", "parent": "3200"},
    {"code": "3230", "name": "Dividends Declared",                  "type": "Equity",    "category": "Dividends",         "parent": "3200"},

    # Other Comprehensive Income – IAS 1
    {"code": "3300", "name": "Other Comprehensive Income Reserves", "type": "Equity",    "category": "Equity Capital",    "is_parent": True, "parent": "3000"},
    {"code": "3310", "name": "Revaluation Surplus",                 "type": "Equity",    "category": "Equity Capital",    "parent": "3300"},
    {"code": "3320", "name": "Foreign Currency Translation Reserve","type": "Equity",    "category": "Equity Capital",    "parent": "3300"},
    {"code": "3330", "name": "Fair Value Reserve",                  "type": "Equity",    "category": "Equity Capital",    "parent": "3300"},
    {"code": "3400", "name": "Drawings / Owner Distributions",      "type": "Equity",    "category": "Drawings",          "parent": "3000"},

    # ══════════════════════════════════════════════════════════
    # REVENUE  4xxx
    # ══════════════════════════════════════════════════════════
    {"code": "4000", "name": "Revenue",                             "type": "Revenue",   "category": "Operating Revenue", "is_parent": True},

    # Operating Revenue – IFRS 15
    {"code": "4100", "name": "Operating Revenue",                   "type": "Revenue",   "category": "Operating Revenue", "is_parent": True, "parent": "4000"},
    {"code": "4110", "name": "Sales Revenue - Goods",               "type": "Revenue",   "category": "Sales Revenue",     "parent": "4100"},
    {"code": "4120", "name": "Sales Revenue - Services",            "type": "Revenue",   "category": "Service Revenue",   "parent": "4100"},
    {"code": "4130", "name": "Sales Returns and Allowances",        "type": "Revenue",   "category": "Sales Revenue",     "parent": "4100"},
    {"code": "4140", "name": "Sales Discounts",                     "type": "Revenue",   "category": "Sales Revenue",     "parent": "4100"},

    # Other Income
    {"code": "4200", "name": "Other Income",                        "type": "Revenue",   "category": "Other Revenue",     "is_parent": True, "parent": "4000"},
    {"code": "4210", "name": "Interest Income",                     "type": "Revenue",   "category": "Interest Income",   "parent": "4200"},
    {"code": "4220", "name": "Dividend Income",                     "type": "Revenue",   "category": "Dividend Income",   "parent": "4200"},
    {"code": "4230", "name": "Rental Income",                       "type": "Revenue",   "category": "Rental Income",     "parent": "4200"},
    {"code": "4240", "name": "Foreign Exchange Gain",               "type": "Revenue",   "category": "Other Revenue",     "parent": "4200"},
    {"code": "4250", "name": "Gain on Disposal of Assets",          "type": "Revenue",   "category": "Gain on Sale of Assets","parent": "4200"},
    {"code": "4260", "name": "Government Grants",                   "type": "Revenue",   "category": "Other Revenue",     "parent": "4200"},
    {"code": "4270", "name": "Miscellaneous Income",                "type": "Revenue",   "category": "Other Revenue",     "parent": "4200"},

    # ══════════════════════════════════════════════════════════
    # EXPENSES  5xxx
    # ══════════════════════════════════════════════════════════
    {"code": "5000", "name": "Expenses",                            "type": "Expense",   "category": "Operating Expense", "is_parent": True},

    # Cost of Sales (IAS 2)
    {"code": "5100", "name": "Cost of Sales",                       "type": "Expense",   "category": "Cost of Sales",     "is_parent": True, "parent": "5000"},
    {"code": "5110", "name": "Cost of Goods Sold - Merchandise",    "type": "Expense",   "category": "Cost of Sales",     "parent": "5100"},
    {"code": "5120", "name": "Cost of Goods Sold - Manufacturing",  "type": "Expense",   "category": "Cost of Sales",     "parent": "5100"},
    {"code": "5130", "name": "Direct Labour",                       "type": "Expense",   "category": "Cost of Sales",     "parent": "5100"},
    {"code": "5140", "name": "Manufacturing Overhead",              "type": "Expense",   "category": "Cost of Sales",     "parent": "5100"},
    {"code": "5150", "name": "Freight and Delivery - Inbound",      "type": "Expense",   "category": "Cost of Sales",     "parent": "5100"},
    {"code": "5160", "name": "Inventory Write-down",                "type": "Expense",   "category": "Cost of Sales",     "parent": "5100"},

    # Selling Expenses
    {"code": "5200", "name": "Selling and Distribution Expenses",   "type": "Expense",   "category": "Operating Expense", "is_parent": True, "parent": "5000"},
    {"code": "5210", "name": "Advertising and Marketing",           "type": "Expense",   "category": "Marketing",         "parent": "5200"},
    {"code": "5220", "name": "Sales Commission",                    "type": "Expense",   "category": "Operating Expense", "parent": "5200"},
    {"code": "5230", "name": "Freight and Delivery - Outbound",     "type": "Expense",   "category": "Operating Expense", "parent": "5200"},
    {"code": "5240", "name": "Customer Entertainment",              "type": "Expense",   "category": "Operating Expense", "parent": "5200"},

    # Administrative Expenses
    {"code": "5300", "name": "Administrative Expenses",             "type": "Expense",   "category": "Operating Expense", "is_parent": True, "parent": "5000"},
    {"code": "5310", "name": "Salaries and Wages",                  "type": "Expense",   "category": "Salaries and Wages","parent": "5300"},
    {"code": "5320", "name": "Employer Payroll Contributions",      "type": "Expense",   "category": "Salaries and Wages","parent": "5300"},
    {"code": "5330", "name": "Rent and Occupancy",                  "type": "Expense",   "category": "Rent Expense",      "parent": "5300"},
    {"code": "5340", "name": "Utilities",                           "type": "Expense",   "category": "Utilities",         "parent": "5300"},
    {"code": "5350", "name": "Office Supplies and Consumables",     "type": "Expense",   "category": "Office Supplies",   "parent": "5300"},
    {"code": "5360", "name": "Telephone and Internet",              "type": "Expense",   "category": "Operating Expense", "parent": "5300"},
    {"code": "5370", "name": "Insurance",                           "type": "Expense",   "category": "Insurance",         "parent": "5300"},
    {"code": "5380", "name": "Professional and Legal Fees",         "type": "Expense",   "category": "Professional Fees", "parent": "5300"},
    {"code": "5390", "name": "Bank Charges and Fees",               "type": "Expense",   "category": "Operating Expense", "parent": "5300"},
    {"code": "5391", "name": "Travel and Accommodation",            "type": "Expense",   "category": "Travel Expense",    "parent": "5300"},
    {"code": "5392", "name": "Training and Development",            "type": "Expense",   "category": "Operating Expense", "parent": "5300"},
    {"code": "5393", "name": "Repairs and Maintenance",             "type": "Expense",   "category": "Repairs and Maintenance","parent": "5300"},
    {"code": "5394", "name": "Printing and Stationery",             "type": "Expense",   "category": "Office Supplies",   "parent": "5300"},
    {"code": "5395", "name": "Subscriptions and Memberships",       "type": "Expense",   "category": "Operating Expense", "parent": "5300"},
    {"code": "5396", "name": "Donations and Sponsorships",          "type": "Expense",   "category": "Operating Expense", "parent": "5300"},
    {"code": "5397", "name": "Vehicle Running Expenses",            "type": "Expense",   "category": "Operating Expense", "parent": "5300"},
    {"code": "5398", "name": "Security Expenses",                   "type": "Expense",   "category": "Operating Expense", "parent": "5300"},
    {"code": "5399", "name": "Miscellaneous Expenses",              "type": "Expense",   "category": "Operating Expense", "parent": "5300"},

    # Depreciation & Amortization (IAS 16 / IAS 38 / IFRS 16)
    {"code": "5400", "name": "Depreciation and Amortization",       "type": "Expense",   "category": "Depreciation",      "is_parent": True, "parent": "5000"},
    {"code": "5410", "name": "Depreciation - Buildings",            "type": "Expense",   "category": "Depreciation",      "parent": "5400"},
    {"code": "5420", "name": "Depreciation - Plant and Machinery",  "type": "Expense",   "category": "Depreciation",      "parent": "5400"},
    {"code": "5430", "name": "Depreciation - Motor Vehicles",       "type": "Expense",   "category": "Depreciation",      "parent": "5400"},
    {"code": "5440", "name": "Depreciation - Equipment",            "type": "Expense",   "category": "Depreciation",      "parent": "5400"},
    {"code": "5450", "name": "Depreciation - ROU Assets",           "type": "Expense",   "category": "Depreciation",      "parent": "5400"},
    {"code": "5460", "name": "Amortization - Intangible Assets",    "type": "Expense",   "category": "Depreciation",      "parent": "5400"},

    # Impairment Losses (IAS 36 / IFRS 9 ECL)
    {"code": "5500", "name": "Impairment Losses",                   "type": "Expense",   "category": "Bad Debts",         "is_parent": True, "parent": "5000"},
    {"code": "5510", "name": "Impairment - Goodwill",               "type": "Expense",   "category": "Bad Debts",         "parent": "5500"},
    {"code": "5520", "name": "ECL - Trade Receivables (IFRS 9)",    "type": "Expense",   "category": "Bad Debts",         "parent": "5500"},
    {"code": "5530", "name": "Impairment - Property and Equipment", "type": "Expense",   "category": "Bad Debts",         "parent": "5500"},

    # Finance Costs
    {"code": "5600", "name": "Finance Costs",                       "type": "Expense",   "category": "Interest Expense",  "is_parent": True, "parent": "5000"},
    {"code": "5610", "name": "Interest Expense - Bank Loans",       "type": "Expense",   "category": "Interest Expense",  "parent": "5600"},
    {"code": "5620", "name": "Interest Expense - Lease Liabilities","type": "Expense",   "category": "Interest Expense",  "parent": "5600"},
    {"code": "5630", "name": "Interest Expense - Other Borrowings", "type": "Expense",   "category": "Interest Expense",  "parent": "5600"},
    {"code": "5640", "name": "Foreign Exchange Loss",               "type": "Expense",   "category": "Operating Expense", "parent": "5600"},

    # Income Tax Expense – IAS 12
    {"code": "5700", "name": "Income Tax Expense",                  "type": "Expense",   "category": "Tax Expense",       "is_parent": True, "parent": "5000"},
    {"code": "5710", "name": "Current Tax Expense",                 "type": "Expense",   "category": "Tax Expense",       "parent": "5700"},
    {"code": "5720", "name": "Deferred Tax Expense / (Credit)",     "type": "Expense",   "category": "Tax Expense",       "parent": "5700"},
]


def seed(clear_existing: bool = True):
    db = SessionLocal()
    try:
        if clear_existing:
            deleted = db.query(AccountingCode).delete()
            db.flush()
            print(f"Cleared {deleted} existing accounting codes.")

        # First pass: insert all codes without parent links
        code_map: dict[str, AccountingCode] = {}
        for acct in ACCOUNTS:
            obj = AccountingCode(
                id=str(uuid.uuid4()),
                code=acct["code"],
                name=acct["name"],
                account_type=acct["type"],
                category=acct["category"],
                is_parent=acct.get("is_parent", False),
                reporting_tag=acct.get("reporting_tag"),
                balance=0.0,
                total_debits=0.0,
                total_credits=0.0,
            )
            db.add(obj)
            code_map[acct["code"]] = obj

        db.flush()

        # Second pass: wire parent_id links
        for acct in ACCOUNTS:
            if "parent" in acct:
                child = code_map[acct["code"]]
                parent = code_map.get(acct["parent"])
                if parent:
                    child.parent_id = parent.id

        db.commit()
        print(f"\nSeeded {len(ACCOUNTS)} IFRS-compliant accounting codes successfully.\n")

        # Summary
        from sqlalchemy import func as sqf
        for atype in ["Asset", "Liability", "Equity", "Revenue", "Expense"]:
            n = db.query(sqf.count(AccountingCode.id)).filter(AccountingCode.account_type == atype).scalar()
            print(f"  {atype:<12}: {n:>3} codes")

        total = db.query(sqf.count(AccountingCode.id)).scalar()
        print(f"\n  {'TOTAL':<12}: {total:>3} codes")

    except Exception as e:
        db.rollback()
        import traceback
        print(f"Error: {e}")
        traceback.print_exc()
        raise
    finally:
        db.close()


if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description="Seed IFRS chart of accounts")
    parser.add_argument("--no-clear", action="store_true", help="Keep existing codes")
    args = parser.parse_args()
    seed(clear_existing=not args.no_clear)
