"""
Register Shopify webhooks for product, refund, and fulfillment events.

Usage:
  python manage.py setup_shopify_webhooks
"""
import json

from django.conf import settings
from django.core.management.base import BaseCommand

import shopify

from products.services import ShopifyService


def _webhook_error_text(webhook) -> str:
    errors = getattr(webhook, "errors", None)
    if errors is None:
        return "unknown error"
    full = getattr(errors, "full_messages", None)
    if callable(full):
        try:
            messages = full()
            if messages:
                return "; ".join(str(m) for m in messages)
        except Exception:
            pass
    if hasattr(errors, "errors"):
        try:
            return str(errors.errors)
        except Exception:
            pass
    return str(errors)


class Command(BaseCommand):
    help = (
        "Register Shopify webhooks for product, refund, and fulfillment events."
    )

    def handle(self, *args, **options):
        if not settings.HOST_URL:
            self.stderr.write(
                self.style.ERROR("HOST_URL is not configured in settings/.env")
            )
            return

        base_url = settings.HOST_URL.rstrip("/")

        # Desired webhooks: topic -> address
        desired = {
            "products/create": f"{base_url}/webhooks/shopify/products-create/",
            "products/update": f"{base_url}/webhooks/shopify/products-update/",
            "products/delete": f"{base_url}/webhooks/shopify/products-delete/",
            "refunds/create": f"{base_url}/webhooks/shopify/refunds-create/",
            "fulfillments/create": f"{base_url}/webhooks/shopify/fulfillments-create/",
            "fulfillments/update": f"{base_url}/webhooks/shopify/fulfillments-update/",
        }

        # Activate a Shopify session using our stored token
        try:
            ShopifyService._activate_session()
        except Exception as e:
            self.stderr.write(self.style.ERROR(f"Failed to activate Shopify session: {e}"))
            return

        existing = shopify.Webhook.find()
        existing_pairs = {(w.topic, w.address) for w in existing}

        created = []
        skipped = []
        for topic, address in desired.items():
            if (topic, address) in existing_pairs:
                skipped.append({"topic": topic, "address": address})
                continue

            wh = shopify.Webhook()
            wh.topic = topic
            wh.address = address
            wh.format = "json"
            if wh.save():
                created.append({"topic": topic, "address": address})
            else:
                detail = _webhook_error_text(wh)
                self.stderr.write(
                    self.style.ERROR(
                        f"Failed to create webhook topic={topic} "
                        f"address={address} errors={detail}"
                    )
                )
                if topic.startswith("fulfillments/"):
                    self.stderr.write(
                        self.style.WARNING(
                            "fulfillments/* webhooks require the read_fulfillments "
                            "scope. Enable it in Shopify Partners, reinstall the app "
                            "(OAuth) so the token is refreshed, then run this command again."
                        )
                    )

        summary = {
            "created": created,
            "skipped_existing": skipped,
        }
        self.stdout.write(
            json.dumps(summary, indent=2, sort_keys=True, default=str)
        )

