"""
Xero API configuration for all branches.
Revenue is extracted via Business Groups tracking category (P&L filtered by tracking).
No line-item pattern matching - all branches use tracking only.
"""
import os
from typing import Dict, List, Optional, Union
from integrations.client_context import get_current_client
from integrations.models import ClientBranch

# Account names to sum for "Cash in Bank" (statement balance from Balance Sheet report).
# Same 3 accounts per Xero instance: Bunbury, Busselton, Mandurah (Nixon Mandurah Pty Ltd: Business Trans Acct, Operating Reserve, Tax & Reserve Account).
CASH_IN_BANK_ACCOUNT_NAMES = [
    "Business Trans Acct",
    "Tax & Reserve Account",
    "Operating Reserve",
]

# department_to_option: dept name -> option name(s). Use list to sum multiple groups (e.g. Mandurah Electrical = Commercial + Residential)
XERO_BRANCH_CONFIG = {
    "branch2": {  # Bunbury
        "enabled": True,
        "tenant_id_env": "XERO_TENANT_ID",
        "department_tracking": {
            "tracking_category_name": "Business Groups",
            "department_to_option": {
                "Residential": "Residential",
                "Air": "Air Conditioning",
                "Solar": "Solar",
                "Commercial": "Commercial"
            }
        },
        "department_to_company_id": {
            "Residential": 2,
            "Air": 3,
            "Solar": 4,
            "Commercial": 5
        }
    },
    "branch1": {  # Busselton
        "enabled": True,
        "tenant_id_env": "XERO_BUSSELTON_TENANT_ID",
        "department_tracking": {
            "tracking_category_name": "Business Groups",
            "department_to_option": {
                "Electrical": "Residential",
                "Air": "Air Conditioning"
            }
        },
        "department_to_company_id": {
            "Electrical": 139,
            "Air": 172
        }
    },
    "branch3": {  # Mandurah - same cash-in-bank account naming as other branches
        "enabled": True,
        "tenant_id_env": "XERO_MANDURAH_TENANT_ID",
        "department_tracking": {
            "tracking_category_name": "Business Groups",
            # Electrical = Commercial + Residential (sum both groups)
            "department_to_option": {
                "Electrical": ["Commercial", "Residential"],
                "Air": "Air Conditioning"
            }
        },
        "department_to_company_id": {
            "Electrical": 2,
            "Air": 35
        }
    }
}

def get_xero_config(branch_id: str) -> Dict:
    """Get Xero configuration for a specific branch."""
    try:
        client = get_current_client()
        if client:
            row = ClientBranch.objects.filter(client=client, branch_id=branch_id).first()
            if row:
                return {
                    "enabled": row.xero_enabled,
                    "tenant_id_env": "XERO_TENANT_ID",
                    "tenant_id": row.xero_tenant_id or "",
                    "department_tracking": {
                        "tracking_category_name": row.xero_tracking_category_name or "Business Groups",
                        "department_to_option": row.xero_department_to_option or {},
                    },
                    "department_to_company_id": row.xero_department_to_company_id or {},
                }
    except Exception:
        pass
    return XERO_BRANCH_CONFIG.get(branch_id)

def get_department_tracking_config(branch_id: str) -> Optional[Dict]:
    """Get department_tracking config (Business Groups mapping)."""
    config = get_xero_config(branch_id)
    if not config:
        return None
    return config.get("department_tracking")

def is_xero_enabled(branch_id: str) -> bool:
    """Check if Xero is enabled for this branch."""
    config = get_xero_config(branch_id)
    return config is not None and config.get("enabled", False)


def get_cash_in_bank_account_names(branch_id: str) -> List[str]:
    """Return account names to sum for cash in bank. Can be overridden per branch if needed."""
    config = get_xero_config(branch_id)
    if config and "cash_in_bank_account_names" in config:
        return config["cash_in_bank_account_names"]
    return CASH_IN_BANK_ACCOUNT_NAMES
