import json
import os
from django.conf import settings
from django.db import connections
from django.http import JsonResponse

def get_api_domains():
    with connections['api_db'].cursor() as cursor:
        cursor.execute("""
            SELECT id, domain_name, base_url, status
            FROM api_domain
        """)

        columns = [col[0] for col in cursor.description]

        return [
            dict(zip(columns, row))
            for row in cursor.fetchall()
        ]




def update_domain_json(request):
    data = get_api_domains()

    json_path = os.path.join(settings.BASE_DIR, "config", "domain.json")
    os.makedirs(os.path.dirname(json_path), exist_ok=True)

    with open(json_path, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=4)

    return JsonResponse({
        "status": True,
        "json_path":json_path,
        "message": "domain.json updated successfully",
        "count": len(data)
    })