"""make_notes_prompt - per-subject notes prompt printer.

Standards: Rule 10 (one canonical writer); Rule 11 (prompt mandatory);
ISO 9001:2015 7.5.3 (documented information); OWASP ASVS 5.1.3
(reject invalid input); Rule 26.
"""
from pathlib import Path

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


PROMPT_PATH = Path.home() / "idealogy" / "prompts" / \
              "MASTER_SHORT_CORE_ANSWER_PROMPT.md"

SUBJECT_WHITELIST = {"PH-9", "CH-9", "BI-9", "MT-9", "EN-9",
                     "UR-9", "IS-9", "TQ-9", "CS-9"}
MEDIUM_WHITELIST = {"EN", "UR"}

SUBJECT_LABEL = {
    "PH-9": "Physics (9th)",
    "CH-9": "Chemistry (9th)",
    "BI-9": "Biology (9th)",
    "MT-9": "Mathematics (9th)",
    "EN-9": "English (9th)",
    "UR-9": "Urdu (9th)",
    "IS-9": "Islamiyat (9th)",
    "TQ-9": "Tarjumatul Quran (9th)",
    "CS-9": "Computer Science (9th)",
}


class Command(BaseCommand):
    help = "Print the short-core notes prompt, filled for one subject."

    def add_arguments(self, parser):
        parser.add_argument("--subject", required=True,
                            help="Subject code: " + ", ".join(sorted(SUBJECT_WHITELIST)))
        parser.add_argument("--medium", required=True,
                            help="EN or UR")
        parser.add_argument("--out", default=None,
                            help="Optional path to write instead of stdout")

    def handle(self, *args, **opts):
        subject = opts["subject"].upper().strip()
        medium = opts["medium"].upper().strip()

        if subject not in SUBJECT_WHITELIST:
            raise CommandError(
                "Unknown subject '" + subject + "'. Allowed: "
                + ", ".join(sorted(SUBJECT_WHITELIST)))
        if medium not in MEDIUM_WHITELIST:
            raise CommandError(
                "Unknown medium '" + medium + "'. Allowed: EN, UR.")

        if not PROMPT_PATH.exists():
            raise CommandError("Prompt file missing: " + str(PROMPT_PATH))

        body = PROMPT_PATH.read_text(encoding="utf-8")

        filled = (
            "\n\n---\n"
            "## FILLED INPUTS (this block is the input for this run)\n\n"
            "- subject: " + subject + "   # " + SUBJECT_LABEL[subject] + "\n"
            "- medium:  " + medium + "\n"
            "- questions: provided separately by the user as an image or text\n"
            "\n"
            "Apply the row '" + subject + "' of SUBJECT GUIDANCE.\n"
            "Apply the '" + medium + "' branch of MEDIUM RULE.\n"
            "Reply with strict JSON only (no prose, no fences).\n"
        )
        out = body + filled

        if opts["out"]:
            Path(opts["out"]).write_text(out, encoding="utf-8")
            self.stdout.write("WROTE: " + opts["out"] + " (" + str(len(out)) + " chars)")
        else:
            self.stdout.write(out)
