import os

from django.core.management.base import BaseCommand

from accounts.models import User
from app.config import settings
from app.config.xero_config import XERO_BRANCH_CONFIG
from integrations.client_context import get_default_client_slug
from integrations.models import Client, ClientBranch, ClientUserMembership


class Command(BaseCommand):
    help = "Bootstrap default client + branch integration config from env/settings."

    def handle(self, *args, **options):
        slug = get_default_client_slug()
        name = os.getenv("DEFAULT_CLIENT_NAME", "Nixon")
        client, _ = Client.objects.get_or_create(
            slug=slug,
            defaults={"name": name, "subdomain": slug, "is_active": True},
        )
        if client.name != name:
            client.name = name
        if not client.subdomain:
            client.subdomain = client.slug
        update_fields = ["name", "subdomain"]
        feats = dict(client.features or {}) if isinstance(client.features, dict) else {}
        if slug == get_default_client_slug() and not feats.get("job_efficiency_csv"):
            feats["job_efficiency_csv"] = True
            client.features = feats
            update_fields.append("features")
        client.save(update_fields=update_fields)

        for branch_id, branch in settings.BRANCHES.items():
            xero_cfg = XERO_BRANCH_CONFIG.get(branch_id, {})
            tenant_id = os.getenv(xero_cfg.get("tenant_id_env", "XERO_TENANT_ID"), "")
            row, _ = ClientBranch.objects.get_or_create(
                client=client,
                branch_id=branch_id,
                defaults={
                    "branch_name": branch.get("name", branch_id),
                    "simpro_api_url": branch.get("api_url", ""),
                    "simpro_api_key": branch.get("api_key", ""),
                    "xero_enabled": bool(xero_cfg.get("enabled", False)),
                    "xero_tenant_id": tenant_id,
                    "xero_tracking_category_name": xero_cfg.get("department_tracking", {}).get("tracking_category_name", "Business Groups"),
                    "xero_department_to_option": xero_cfg.get("department_tracking", {}).get("department_to_option", {}),
                    "xero_department_to_company_id": xero_cfg.get("department_to_company_id", {}),
                },
            )
            # Keep branch names/keys in sync when rerun
            row.branch_name = branch.get("name", row.branch_name)
            row.simpro_api_url = branch.get("api_url", row.simpro_api_url)
            row.simpro_api_key = branch.get("api_key", row.simpro_api_key)
            row.xero_tenant_id = tenant_id or row.xero_tenant_id
            row.save()

        for user in User.objects.all():
            ClientUserMembership.objects.get_or_create(client=client, user=user)

        self.stdout.write(self.style.SUCCESS(f"Bootstrapped client '{client.slug}' with {client.branches.count()} branches"))
