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

import frappe
from frappe import _


def execute(filters=None):
	"""Main function for report execution"""
	columns = get_columns(filters)
	data = get_data(filters)

	return columns, data


def get_columns(filters=None):
	"""Get report columns definition"""
	return [
		{
			"label": _("Purchase Invoice"),
			"fieldname": "purchase_invoice",
			"fieldtype": "Link",
			"options": "Purchase Invoice",
			"width": 160
		},
		{
			"label": _("Act Type"),
			"fieldname": "act_type",
			"fieldtype": "Data",
			"width": 120
		},
		{
			"label": _("Counterparty"),
			"fieldname": "counterparty",
			"fieldtype": "Data",
			"width": 240
		},
		{
			"label": _("VOEN"),
			"fieldname": "voen",
			"fieldtype": "Data",
			"width": 130
		},
		{
			"label": _("FIN"),
			"fieldname": "fin",
			"fieldtype": "Data",
			"width": 130
		},
		{
			"label": _("Amount"),
			"fieldname": "amount",
			"fieldtype": "Currency",
			"width": 140
		}
	]


def get_data(filters=None):
	"""Get report data"""
	filters = filters or {}
	conditions = ""

	if filters.get("company"):
		conditions += " AND pi.company = %(company)s"

	if filters.get("from_date"):
		conditions += " AND pi.posting_date >= %(from_date)s"

	if filters.get("to_date"):
		conditions += " AND pi.posting_date <= %(to_date)s"

	rows = frappe.db.sql(f"""
		SELECT
			pi.name AS purchase_invoice,
			pi.act_type,
			pi.agricultural_country,
			pi.supplier_name,
			pi.grand_total,
			sup.supplier_type,
			sup.tax_id,
			sup.fin
		FROM
			`tabPurchase Invoice` pi
		LEFT JOIN
			`tabSupplier` sup ON sup.name = pi.supplier
		WHERE
			pi.docstatus = 1
			AND pi.agricultural_goods = 1
			AND pi.update_stock = 1
			{conditions}
		ORDER BY
			pi.posting_date DESC, pi.name
	""", filters, as_dict=1)

	data = []
	for r in rows:
		# Column 2-4 depend on the act type / supplier type:
		#   Import          -> counterparty = country, VOEN/FIN empty
		#   Individual       -> counterparty = full name (ФИО), FIN filled
		#   Company (MMC)    -> counterparty = company name, VOEN filled
		if r.act_type == "Import":
			counterparty = r.agricultural_country or ""
			voen = ""
			fin = ""
		elif r.supplier_type == "Individual":
			counterparty = r.supplier_name or ""
			voen = ""
			fin = r.fin or ""
		else:
			counterparty = r.supplier_name or ""
			voen = r.tax_id or ""
			fin = ""

		data.append({
			"purchase_invoice": r.purchase_invoice,
			"act_type": r.act_type or "",
			"counterparty": counterparty,
			"voen": voen,
			"fin": fin,
			"amount": r.grand_total or 0
		})

	return data
