"""Guard sentence-style Indonesian / English copy so particles like di/dan/untuk/dari and and/for/from stay lowercase unless they start a sentence."""
from __future__ import annotations

import argparse
import json
import re
from datetime import datetime
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
REPORT_PATH = ROOT / "data" / "copy_style_guard_latest.json"
TARGETS = {
    "id_ID": {"file": ROOT / "lang" / "id_ID.json", "words": ["Di", "Dan", "Untuk", "Dari"]},
    "en_US": {"file": ROOT / "lang" / "en_US.json", "words": ["And", "For", "From"]},
}
SENTENCE_SUFFIXES = ("_hint", "_subtitle", "_desc", "_desc_long", "_message", "_intro", "_note", "_text", "_placeholder", "_policy", "_slogan", "_status", "_summary", "_title_hint", "_flow_hint")
EXTRA_KEYS = {"app_subtitle", "settings_subtitle", "enterprise_subtitle", "cloud_subtitle", "shared_files_desc", "login_front_hint", "login_first_hint", "login_existing_hint", "login_create_hint", "login_hero_subtitle", "login_panel_subtitle", "login_remember_hint", "forgot_password_hint", "forgot_password_flow_hint", "forgot_password_verify_hint", "forgot_password_reset_hint", "login_slogan"}

def build_report() -> dict:
    issues = []
    checked = 0
    for lang, meta in TARGETS.items():
        payload = json.loads(meta["file"].read_text(encoding="utf-8"))
        words = set(meta["words"])
        for key, value in payload.items():
            if not isinstance(value, str) or not (key.endswith(SENTENCE_SUFFIXES) or key in EXTRA_KEYS):
                continue
            checked += 1
            for sentence in re.split(r"[\n]+|(?<=[.!?])\s+", value):
                sentence = sentence.strip()
                if not sentence:
                    continue
                parts = sentence.split()
                for idx, token in enumerate(parts[1:], start=1):
                    bare = re.sub(r"^[^A-Za-zÀ-ÿ]*|[^A-Za-zÀ-ÿ]*$", "", token)
                    if bare in words:
                        issues.append({"language": lang, "key": key, "value": value, "problem": f"'{bare}' should be lowercase when not sentence-initial"})
                        break
                else:
                    continue
                break
    return {
        "checked_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "checked_entries": checked,
        "status": "OK" if not issues else "FAILED",
        "issues": issues[:200],
        "rule": {
            "id_ID": "di / dan / untuk / dari are lowercase unless sentence-initial",
            "en_US": "and / for / from are lowercase unless sentence-initial",
        },
    }

def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--write-report", action="store_true")
    args = parser.parse_args()
    report = build_report()
    if args.write_report:
        REPORT_PATH.parent.mkdir(parents=True, exist_ok=True)
        REPORT_PATH.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
    print("NexaOffice Copy Style Guard")
    print(f"- Checked entries: {report['checked_entries']}")
    print(f"- Status: {report['status']}")
    if report["issues"]:
        for item in report["issues"][:20]:
            print(f"  {item['language']} {item['key']}: {item['problem']}")
    if args.write_report:
        print(f"- Report: {REPORT_PATH.relative_to(ROOT)}")
    return 0 if report["status"] == "OK" else 1

if __name__ == "__main__":
    raise SystemExit(main())
