import re

import frappe

# 223.1–223.5: IBAN (AZ + 2 digits + 4 uppercase letters + 20 alphanumeric = 28 chars)
# Оставляем "AZ" в начале, маскируем остальные 26 символов
_IBAN_RE = re.compile(r"AZ\d{2}[A-Z]{4}[A-Z0-9]{20}")
# 223.6: номер карты — любая последовательность 10+ цифр подряд
_DIGITS_RE = re.compile(r"\d{10,}")

MASK_IBAN = {"223.1", "223.2", "223.3", "223.4", "223.5"}
MASK_CARD = {"223.6"}


def _mask(account_name, account_number):
    if account_number in MASK_IBAN:
        account_name = _IBAN_RE.sub(lambda m: "AZ" + "X" * (len(m.group()) - 2), account_name)
    if account_number in MASK_CARD:
        account_name = _DIGITS_RE.sub(lambda m: "X" * len(m.group()), account_name)
    return account_name


def _build_node(account, children_of):
    node = {}

    if account.account_number:
        node["account_number"] = account.account_number
    if account.root_type:
        node["root_type"] = account.root_type
    if account.is_group:
        node["is_group"] = 1
    if account.account_type:
        node["account_type"] = account.account_type

    for child in children_of.get(account.name, []):
        key = _mask(child.account_name, child.account_number or "")
        node[key] = _build_node(child, children_of)

    return node


@frappe.whitelist()
def export_chart_of_accounts():
    accounts = frappe.get_all(
        "Account",
        fields=["name", "account_name", "account_number", "parent_account",
                "root_type", "account_type", "is_group"],
        order_by="lft",
    )

    children_of = {}
    roots = []

    for a in accounts:
        if not a.parent_account:
            roots.append(a)
        else:
            children_of.setdefault(a.parent_account, []).append(a)

    tree = {}
    for root in roots:
        key = _mask(root.account_name, root.account_number or "")
        tree[key] = _build_node(root, children_of)

    return {
        "country_code": "az",
        "name": "Azerbaijan Republic",
        "tree": tree,
    }
