"""make_glossary_prompt — print MASTER_UNIVERSAL_GLOSSARY_PROMPT.md
with a caller-supplied list of words substituted.

Usage:
    python manage.py make_glossary_prompt --words-file /path/to/words.txt [--out OUT]
    python manage.py make_glossary_prompt word1 word2 word3 ...

The words file is one word per line (blank lines ignored, comments starting
with # ignored). The printer fills __WORDS__ and outputs either to stdout
or to a file.

Standards:
  Beck/McKeown/Kucan three-tier vocabulary;
  Marzano Six-Step Process; Frayer Model; Hayden et al. 2019;
  ISO 24495-1:2023 (plain language); GOV.UK content design;
  WCAG 2.2 AA (esp. SC 3.1.5 Reading Level);
  AERA/APA/NCME 2014 Std 13.7; Rule G; Rule 10; Rule 11.
"""
from pathlib import Path as _Path

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


PROMPT_PATH = _Path("/home/orkoworo/idealogy/prompts/MASTER_UNIVERSAL_GLOSSARY_PROMPT.md")
MAX_WORDS_PER_BATCH = 30


class Command(BaseCommand):
    help = "Print MASTER_UNIVERSAL_GLOSSARY_PROMPT.md with words substituted."

    def add_arguments(self, parser):
        parser.add_argument("words", nargs="*", type=str,
                            help="Words as positional args (optional).")
        parser.add_argument("--words-file", default=None, type=str,
                            help="Path to a file with one word per line.")
        parser.add_argument("--out", default=None, type=str,
                            help="Optional output file (default: stdout).")

    def handle(self, *args, **opts):
        words = list(opts["words"] or [])
        if opts["words_file"]:
            p = _Path(opts["words_file"])
            if not p.exists():
                raise CommandError("Words file not found: " + str(p))
            for line in p.read_text(encoding="utf-8").splitlines():
                line = line.strip()
                if not line or line.startswith("#"):
                    continue
                words.append(line)

        if not words:
            raise CommandError("No words supplied (use positional args or --words-file).")
        if len(words) > MAX_WORDS_PER_BATCH:
            raise CommandError(
                f"Too many words ({len(words)}). Max is {MAX_WORDS_PER_BATCH} "
                "per batch (PMBOK 6.4: keep Gemini output under 8K tokens).")

        # de-duplicate, preserve order
        seen = set()
        unique = []
        for w in words:
            lw = w.lower()
            if lw in seen:
                continue
            seen.add(lw)
            unique.append(w)

        if not PROMPT_PATH.exists():
            raise CommandError("Prompt file missing: " + str(PROMPT_PATH))
        template = PROMPT_PATH.read_text(encoding="utf-8")

        word_lines = "\n".join(f"- {w}" for w in unique)
        filled = template.replace("__WORDS__", word_lines)

        if opts["out"]:
            outp = _Path(opts["out"])
            outp.parent.mkdir(parents=True, exist_ok=True)
            outp.write_text(filled, encoding="utf-8")
            self.stdout.write(f"wrote {outp} ({outp.stat().st_size} bytes) for {len(unique)} word(s).")
        else:
            self.stdout.write(filled)
            self.stderr.write(f"[stderr] filled for {len(unique)} unique word(s).")
