"""
company_context_service.py
--------------------------
Single utility used by any document/report service that needs company
identity details (name, address, logo, tax numbers, footer text, etc.).

Resolution order:
  1. Company table (linked via Branch.company_id)
  2. AppSetting singleton (legacy fallback for existing deployments)
  3. Hard-coded defaults

This means new multi-tenant deployments get their Company data on all
documents automatically, while single-tenant deployments already using
AppSetting continue to work unchanged.
"""
from typing import Optional, Dict, Any
from sqlalchemy.orm import Session


def get_company_context(branch_id: Optional[str], db: Session) -> Dict[str, Any]:
    """
    Return a normalised dict of company identity fields for use in
    document headers, PDF generation, and API responses.

    Keys returned:
        company_name, legal_name, company_code
        registration_number, tax_identification_number, vat_registration_number
        address_line1, address_line2, city, state, country, postal_code
        phone, phone2, fax, email, website
        logo_url, primary_color
        currency, currency_symbol, default_vat_rate
        invoice_footer, receipt_footer, po_terms
        timezone
    """
    ctx: Dict[str, Any] = {
        "company_name": "Company Name",
        "legal_name": "",
        "company_code": "",
        "registration_number": "",
        "tax_identification_number": "",
        "vat_registration_number": "",
        "address_line1": "",
        "address_line2": "",
        "city": "",
        "state": "",
        "country": "",
        "postal_code": "",
        "phone": "",
        "phone2": "",
        "fax": "",
        "email": "",
        "website": "",
        "logo_url": "",
        "primary_color": "#0d6efd",
        "currency": "BWP",
        "currency_symbol": "P",
        "default_vat_rate": 14.0,
        "invoice_footer": "",
        "receipt_footer": "",
        "po_terms": "",
        "timezone": "Africa/Gaborone",
    }

    # ── 1. Try Company table via branch ──────────────────────────────────────
    company = None
    if branch_id:
        try:
            from app.models.branch import Branch
            from app.models.company import Company
            branch = db.query(Branch).filter(Branch.id == branch_id).first()
            if branch and branch.company_id:
                company = db.query(Company).filter(Company.id == branch.company_id).first()
        except Exception:
            pass

    if company:
        _currency_symbols = {
            "BWP": "P", "ZAR": "R", "USD": "$", "EUR": "€",
            "GBP": "£", "KES": "KSh", "ZMW": "ZK",
        }
        ctx.update({
            "company_name":             company.name or ctx["company_name"],
            "legal_name":               company.legal_name or company.name or "",
            "company_code":             company.company_code or "",
            "registration_number":      company.registration_number or "",
            "tax_identification_number": company.tax_identification_number or "",
            "vat_registration_number":  company.vat_registration_number or "",
            "address_line1":            company.address_line1 or "",
            "address_line2":            company.address_line2 or "",
            "city":                     company.city or "",
            "state":                    company.state or "",
            "country":                  company.country or "",
            "postal_code":              company.postal_code or "",
            "phone":                    company.phone or "",
            "phone2":                   company.phone2 or "",
            "fax":                      company.fax or "",
            "email":                    company.email or "",
            "website":                  company.website or "",
            "logo_url":                 company.logo_url or "",
            "primary_color":            company.primary_color or "#0d6efd",
            "currency":                 company.currency or "BWP",
            "currency_symbol":          _currency_symbols.get(company.currency or "BWP", "P"),
            "default_vat_rate":         float(company.default_vat_rate or 14.0),
            "invoice_footer":           company.invoice_footer or "",
            "receipt_footer":           company.receipt_footer or "",
            "po_terms":                 company.po_terms or "",
            "timezone":                 company.timezone or "Africa/Gaborone",
        })
        # Convenience alias used by legacy document templates
        ctx["company_address"] = ", ".join(filter(None, [
            company.address_line1, company.address_line2,
            company.city, company.state, company.country,
        ]))
        return ctx

    # ── 2. Fallback: AppSetting singleton ────────────────────────────────────
    try:
        from app.models.app_setting import AppSetting
        instance = AppSetting.get_instance(db)
        if instance:
            _currency_symbols = {
                "BWP": "P", "ZAR": "R", "USD": "$", "EUR": "€",
                "GBP": "£", "KES": "KSh", "ZMW": "ZK",
            }
            currency = getattr(instance, "currency", "BWP") or "BWP"
            ctx.update({
                "company_name":            getattr(instance, "company_name", "") or ctx["company_name"],
                "vat_registration_number": getattr(instance, "vat_registration_number", "") or "",
                "logo_url":                getattr(instance, "company_logo_url", "") or "",
                "currency":                currency,
                "currency_symbol":         _currency_symbols.get(currency, "P"),
                "company_address":         getattr(instance, "address", "") or "",
                "phone":                   getattr(instance, "phone", "") or "",
                "email":                   getattr(instance, "email", "") or "",
            })
    except Exception:
        pass

    if "company_address" not in ctx:
        ctx["company_address"] = ""

    return ctx
