"""Create or update the real AGA proposal template in project ``aga``."""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

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

from snapfile.core import ids
from snapfile.projects.aga_seed import seed_aga


class Command(BaseCommand):
    help = "Build template aga-proposal (all sheets, variables, conditions). Images come from --assets-dir."

    def add_arguments(self, parser: Any) -> None:
        parser.add_argument("--slug", default="aga")
        parser.add_argument("--assets-dir", default=str(Path(settings.BASE_DIR) / "var" / "aga-assets"))
        parser.add_argument("--sample-data", help="JSON file saved as the template's test data")
        parser.add_argument("--no-publish", action="store_true")

    def handle(self, *args: Any, **opts: Any) -> None:
        sample = json.loads(Path(opts["sample_data"]).read_text(encoding="utf-8")) if opts["sample_data"] else None
        res = seed_aga(opts["slug"], Path(opts["assets_dir"]), sample, publish=not opts["no_publish"])
        self.stdout.write(f"project:  {res.project.slug}")
        self.stdout.write(f"template: {res.template.key} ({ids.encode('tpl', res.template.id)})")
        if res.version is not None:
            self.stdout.write(f"version:  v{res.version.number}")
        if res.missing_assets:
            self.stdout.write(self.style.WARNING(f"placeholders for {len(res.missing_assets)} missing images"))
