"""Management command to summarise coverage results and update the badge."""

from __future__ import annotations

import json
from pathlib import Path

from django.core.management.base import BaseCommand, CommandError

from utils.coverage import coverage_color, load_summary, render_badge


class Command(BaseCommand):
    """Compute aggregate test coverage from a JSON report."""

    help = "Compute overall test coverage and refresh the SVG badge."

    def add_arguments(self, parser) -> None:  # pragma: no cover - exercised in tests
        parser.add_argument(
            "--coverage-json",
            default="coverage.json",
            help="Path to the JSON report generated by 'coverage json'.",
        )
        parser.add_argument(
            "--badge-path",
            default="coverage.svg",
            help="Destination for the SVG badge.",
        )
        parser.add_argument(
            "--label",
            default="coverage",
            help="Label to display on the SVG badge.",
        )

    def handle(self, *args, **options):
        core_dir = Path(__file__).resolve().parents[2]
        project_root = core_dir.parent

        coverage_path = Path(options.get("coverage_json") or "coverage.json")
        if not coverage_path.is_absolute():
            coverage_path = project_root / coverage_path
        if not coverage_path.exists():
            raise CommandError(f"Coverage report {coverage_path} does not exist")

        try:
            summary = load_summary(coverage_path)
        except ValueError as exc:
            raise CommandError(str(exc)) from exc

        output = json.dumps(summary.to_dict(), indent=2, sort_keys=True)
        self.stdout.write(output)

        badge_path = Path(options.get("badge_path") or "coverage.svg")
        if not badge_path.is_absolute():
            badge_path = project_root / badge_path
        badge_path.parent.mkdir(parents=True, exist_ok=True)

        label = str(options.get("label") or "coverage")
        badge_value = f"{summary.percent:.1f}%"
        badge_svg = render_badge(label, badge_value, coverage_color(summary.percent))
        badge_path.write_text(badge_svg + "\n", encoding="utf-8")
