import json
import requests
import fastjsonschema
from subprocess import run, PIPE

from django.conf import settings

from django.core.management.base import BaseCommand


class Command(BaseCommand):
    help = "Fetches the event schema JSON from the API and saves it to disk. Used during development."

    def handle(self, *args, **options):
        # Fetch the event schema JSON from the API and save it to disk
        json_result = requests.get(
            "https://raw.githubusercontent.com/getsentry/sentry-data-schemas/main/relay/event.schema.json")
        json_result.raise_for_status()

        with open(settings.BASE_DIR / "api/event.schema.json", "w") as f:
            f.write(json_result.text)

        # Fetch the license from GitHub and save it to disk (with annotation about the source)
        license_url = "https://raw.githubusercontent.com/getsentry/sentry-data-schemas/main/LICENSE"
        license_result = requests.get(license_url)
        license_result.raise_for_status()

        with open(settings.BASE_DIR / "api/LICENSE", "w") as f:
            f.write("""This licence applies to the file: event.schema.json
The source of this file is: %s

""" % license_url)
            f.write(license_result.text)

        # Generate fastjsonschema code from the schema and save it to disk
        schema = json.loads(json_result.text)

        # use_formats=False for "uint64", see https://github.com/horejsek/python-fastjsonschema/issues/108
        # use_default=False to avoid fastjsonschema adding default values to the data it validates (bwegh)
        code = fastjsonschema.compile_to_code(schema, use_formats=False, use_default=False)

        with open(settings.BASE_DIR / "bugsink/event_schema.py", "w") as f:
            f.write("""# This file is generated by fetch_event_schema_json.py
# it is based on api/event.schema.json
# the following license applies:
""")
            f.write("\n".join("# " + line for line in license_result.text.splitlines()) + "\n\n")
            f.write(code)

        # put it through 'black' to make it fit on screen at least, and perhaps to get useable diffs too.
        # (we don't bother putting it in requirements.txt, since it's used so rarely)
        run(["black", settings.BASE_DIR / "bugsink/event_schema.py"], stdout=PIPE, stderr=PIPE)
