from apps.accounting.models import Account
from apps.fleet.models import Vehicle, VehicleAuditEvent
from apps.tenancy.models import Company


FLEET_DEFAULT_ACCOUNTS = [
    ("1010", "Cash in Hand", Account.AccountType.ASSET, Account.ControlRole.CASH),
    ("1020", "Main Bank Account", Account.AccountType.ASSET, Account.ControlRole.BANK),
    ("1110", "Sundry Debtors (Customers)", Account.AccountType.ASSET, Account.ControlRole.SUNDRY_DEBTORS),
    ("1170", "Driver & Employee Advances", Account.AccountType.ASSET, Account.ControlRole.EMPLOYEE_ADVANCE),
    ("1180", "Fuel & Lubricants Inventory", Account.AccountType.ASSET, Account.ControlRole.INVENTORY),
    ("1185", "Rented Owner / Supplier Advances", Account.AccountType.ASSET, Account.ControlRole.SUPPLIER_ADVANCE),
    ("1350", "Vehicle Rental Security Deposit (Asset)", Account.AccountType.ASSET, Account.ControlRole.NONE),
    ("2010", "Sundry Creditors (Suppliers)", Account.AccountType.LIABILITY, Account.ControlRole.SUNDRY_CREDITORS),
    ("2070", "Customer Vehicle Hire Advances (Liability)", Account.AccountType.LIABILITY, Account.ControlRole.CUSTOMER_ADVANCE),
    ("2250", "Customer Vehicle Deposit (Liability)", Account.AccountType.LIABILITY, Account.ControlRole.NONE),
    ("4150", "Vehicle Hire & Transport Income", Account.AccountType.INCOME, Account.ControlRole.OTHER_INCOME),
    ("5305", "Project Transport & Equipment WIP Cost", Account.AccountType.EXPENSE, Account.ControlRole.PROJECT_WIP),
    ("5310", "Rented Vehicle Hire Expense", Account.AccountType.EXPENSE, Account.ControlRole.DIRECT_EXPENSES),
    ("5320", "Vehicle Fuel Expense", Account.AccountType.EXPENSE, Account.ControlRole.DIRECT_EXPENSES),
    ("5330", "Vehicle Repair & Maintenance Expense", Account.AccountType.EXPENSE, Account.ControlRole.OFFICE_EXPENSES),
    ("5990", "Internal Fleet Cost Recovery Clearing", Account.AccountType.EXPENSE, Account.ControlRole.NONE),
]


class FleetAccountResolver:
    """Resolves existing company ledger accounts by ControlRole or creates idempotent defaults."""

    @staticmethod
    def ensure_fleet_accounts(company: Company) -> dict[str, Account]:
        out: dict[str, Account] = {}
        for code, name, atype, role in FLEET_DEFAULT_ACCOUNTS:
            acc = Account.objects.filter(company=company, code=code, is_group=False, is_active=True).first()
            if not acc and role != Account.ControlRole.NONE:
                acc = Account.objects.filter(company=company, control_role=role, is_group=False, is_active=True).first()
            if not acc:
                acc, _ = Account.objects.get_or_create(
                    company=company,
                    code=code,
                    defaults={"name": name, "account_type": atype, "control_role": role},
                )
            out[code] = acc
        return out

    @staticmethod
    def resolve_counter_account(company: Company, *, payment_method: str, party=None, explicit_account_id=None) -> Account:
        if explicit_account_id:
            acc = Account.objects.filter(company=company, id=explicit_account_id, is_group=False, is_active=True).first()
            if not acc:
                raise ValueError("Selected Cash/Bank/Control ledger account not found in company.")
            if payment_method == "CASH" and acc.control_role != Account.ControlRole.CASH and acc.account_type != Account.AccountType.ASSET:
                raise ValueError("Cash transaction must use a Cash ledger account.")
            return acc
        accounts = FleetAccountResolver.ensure_fleet_accounts(company)
        if payment_method == "CASH":
            return Account.objects.filter(company=company, control_role=Account.ControlRole.CASH, is_group=False, is_active=True).first() or accounts["1010"]
        if payment_method == "BANK":
            return Account.objects.filter(company=company, control_role=Account.ControlRole.BANK, is_group=False, is_active=True).first() or accounts["1020"]
        if payment_method == "CREDIT":
            if not party:
                raise ValueError("Credit transactions strictly require a registered Customer or Supplier party.")
            if party.party_type == "CUSTOMER":
                return Account.objects.filter(company=company, control_role=Account.ControlRole.SUNDRY_DEBTORS, is_group=False, is_active=True).first() or accounts["1110"]
            return Account.objects.filter(company=company, control_role=Account.ControlRole.SUNDRY_CREDITORS, is_group=False, is_active=True).first() or accounts["2010"]
        raise ValueError(f"Unsupported payment_method: {payment_method}")


def record_fleet_audit(*, company: Company, actor, action: str, entity_type: str, entity_id: str, vehicle: Vehicle | None = None, metadata: dict | None = None):
    return VehicleAuditEvent.objects.create(
        company=company,
        vehicle=vehicle,
        actor=actor,
        action=action,
        entity_type=entity_type,
        entity_id=str(entity_id),
        metadata=metadata or {},
    )

