#!/usr/bin/env python3
"""Strip <<<Q:N>>> and related artifacts from questions JSON files."""
from __future__ import annotations

import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
SCRIPTS = Path(__file__).resolve().parent
if str(SCRIPTS) not in sys.path:
    sys.path.insert(0, str(SCRIPTS))

from clean_text import clean_question, clean_review_item

QUESTIONS = ROOT / "data" / "questions.json"
REVIEW = ROOT / "data" / "questions-review.json"


def main() -> int:
    q_changed = 0
    if QUESTIONS.exists():
        questions = json.loads(QUESTIONS.read_text(encoding="utf-8"))
        for q in questions:
            if clean_question(q):
                q_changed += 1
        QUESTIONS.write_text(
            json.dumps(questions, ensure_ascii=False, indent=2),
            encoding="utf-8",
        )
        print(f"Cleaned {QUESTIONS.name}: {q_changed}/{len(questions)} questions updated")

    r_changed = 0
    if REVIEW.exists():
        review = json.loads(REVIEW.read_text(encoding="utf-8"))
        for item in review:
            if clean_review_item(item):
                r_changed += 1
        REVIEW.write_text(
            json.dumps(review, ensure_ascii=False, indent=2),
            encoding="utf-8",
        )
        print(f"Cleaned {REVIEW.name}: {r_changed}/{len(review)} items updated")

    return 0


if __name__ == "__main__":
    sys.exit(main())
