"""Clean the meanings of already-built meaning packs in place (wiki markup, HTML entities, mojibake).

Usage:
  clean-pack-meanings.py <meaning pack dir>...

Applies packlib.clean_meaning to every meaning of the `meanings` table: `[[target|label]]` becomes the
label, entities are decoded, mojibake is repaired, and a meaning that can not be repaired is dropped
(so is a duplicate that cleaning creates). A row that loses all its meanings is dropped. Row order,
shard files and their names stay as they are; pack.json changes only when the row count does.
curated.json is never changed; a damaged curated meaning is only reported. A second run changes nothing.
New packs are cleaned by their converters already (README "Building the packs").
"""
import json
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import packlib  # noqa: E402

EXAMPLES = 10


def clean_shard(path, stats):
    """Rewrites one shard file when a meaning of it changes."""
    lines = path.read_text(encoding="utf-8").split("\n")
    trailing_newline = lines and lines[-1] == ""
    if trailing_newline:
        lines.pop()
    result = []
    changed = False
    for line in lines:
        key, *meanings = line.split("\t")
        kept = []
        for meaning in meanings:
            cleaned = packlib.clean_meaning(meaning)
            if cleaned is None or cleaned in kept:
                stats["dropped"] += 1
                stats["examples"].append((key, meaning, None))
            else:
                if cleaned != meaning:
                    stats["repaired"] += 1
                    stats["examples"].append((key, meaning, cleaned))
                kept.append(cleaned)
        if kept != meanings:
            stats["touched"] += 1
            changed = True
        if kept:
            result.append("\t".join([key, *kept]))
        else:
            stats["rows_dropped"] += 1
            changed = True
    if changed:
        path.write_text("\n".join(result) + ("\n" if result and trailing_newline else ""), encoding="utf-8")


def clean_pack(pack_dir):
    pack = Path(pack_dir)
    manifest_path = pack / "pack.json"
    manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    if manifest.get("kind") != "meanings":
        raise SystemExit(f"{pack}: not a meaning pack")
    stats = {"touched": 0, "repaired": 0, "dropped": 0, "rows_dropped": 0, "examples": []}
    rows = 0
    for shard in sorted((pack / "meanings").glob("*.tsv")):
        if shard.name.startswith("._"):
            continue
        clean_shard(shard, stats)
        rows += sum(1 for line in shard.read_text(encoding="utf-8").split("\n") if line)
    details = manifest.get("tableDetails", {}).get("meanings")
    if details is not None and details.get("rows") != rows:
        details["rows"] = rows
        packlib._write_manifest(manifest_path, manifest)
    curated = pack / "curated.json"
    if curated.exists():
        try:
            packlib.check_curated(json.loads(curated.read_text(encoding="utf-8")), f"curated list of {pack.name}")
        except SystemExit as error:
            print(f"WARNING {error}")
    print(f"{pack.name}: {stats['touched']} rows touched, {stats['repaired']} meanings repaired, "
          f"{stats['dropped']} meanings dropped, {stats['rows_dropped']} rows dropped.")
    step = max(1, len(stats["examples"]) // EXAMPLES)
    for key, before, after in stats["examples"][::step][:EXAMPLES]:
        print(f"  {key}: {before!r} -> {after!r}")
    return stats


def main(arguments):
    if not arguments:
        raise SystemExit(__doc__)
    for pack_dir in arguments:
        clean_pack(pack_dir)


if __name__ == "__main__":
    main(sys.argv[1:])
