import ssl
import urllib.request
import urllib.parse
import json

from django.core.management.base import BaseCommand

_ssl_ctx = ssl.create_default_context()
_ssl_ctx.check_hostname = False
_ssl_ctx.verify_mode = ssl.CERT_NONE

from apps.publications.models import CSISPublication

CSIS_API_BASE = "https://api.csis.or.id/api/publications/"
PAGE_SIZE = 50


def fetch_page(url):
    req = urllib.request.Request(url, headers={"Accept": "application/json"})
    with urllib.request.urlopen(req, timeout=15, context=_ssl_ctx) as resp:
        return json.loads(resp.read().decode())


def record_from_item(item):
    cat = item.get("category_info") or {}
    return {
        "title": item["title"],
        "slug": item["slug"],
        "date_publish": item.get("date_publish") or None,
        "authors": [
            {"id": a["id"], "name": a["name"], "slug": a["slug"],
             "position": a.get("position", ""), "profile_img": a.get("profile_img", "")}
            for a in item.get("authors", [])
        ],
        "topics": [
            {"id": t["id"], "name": t["name"], "slug": t["slug"]}
            for t in item.get("topic", [])
        ],
        "category_name": cat.get("name", ""),
        "category_slug": cat.get("slug", ""),
        "image": item.get("image") or "",
        "file_url": item.get("file") or "",
        "description": item.get("description") or "",
        "viewed": item.get("viewed") or 0,
        "download_count": item.get("download_count") or 0,
    }


class Command(BaseCommand):
    help = "Fetch all publications from api.csis.or.id and upsert into CSISPublication table."

    def handle(self, *args, **options):
        url = f"{CSIS_API_BASE}?page_size={PAGE_SIZE}"
        total_synced = 0
        page = 1

        while url:
            self.stdout.write(f"Fetching page {page}: {url}")
            try:
                data = fetch_page(url)
            except Exception as exc:
                self.stderr.write(f"Error fetching page {page}: {exc}")
                break

            for item in data.get("results", []):
                defaults = record_from_item(item)
                CSISPublication.objects.update_or_create(
                    csis_id=item["id"],
                    defaults=defaults,
                )
                total_synced += 1

            url = data.get("next")
            page += 1

        self.stdout.write(self.style.SUCCESS(f"Done. Synced {total_synced} publications."))
