# Copyright (c) 2026, JeyERP and contributors
# For license information, please see license.txt

import frappe
from frappe import _
from frappe.model.document import Document


# Standard fields the parser needs depending on the chosen amount_mode.
# Date is always required.
_REQUIRED_BY_MODE = {
	"Single column with sign": ("Date", "Reference Number", "Amount"),
	"Separate debit/credit columns": ("Date", "Reference Number", "Debit", "Credit"),
	"Single column + direction column": ("Date", "Reference Number", "Amount", "Direction"),
}


class BankIntegrationExcelPreset(Document):
	def validate(self):
		self._validate_required_mappings()
		self._validate_direction_values()

	def _validate_required_mappings(self):
		mode = self.amount_mode or "Separate debit/credit columns"
		required = _REQUIRED_BY_MODE.get(mode, ())
		mapped = {
			(row.standard_field or "").strip()
			for row in (self.column_mappings or [])
			if row.excel_column and row.standard_field
		}
		missing = [f for f in required if f not in mapped]
		if missing:
			frappe.throw(_(
				"Amount Mode '{0}' requires these Standard Fields to be mapped in the Column Mappings table: {1}. "
				"Add a row for each missing field."
			).format(mode, ", ".join(missing)))

	def _validate_direction_values(self):
		if self.amount_mode != "Single column + direction column":
			return
		if not (self.direction_debit_values or "").strip() and not (self.direction_credit_values or "").strip():
			frappe.throw(_(
				"Mode 'Single column + direction column' requires at least one of "
				"'Debit Values' or 'Credit Values' to be filled (comma-separated)."
			))
