"""Convert CP1251-encoded .txt files in root to UTF-8.

Usage:
  python convert_cp1251_to_utf8.py --root "A:\\WorkProj\\OverPunk\\WikiServ\\Картотека"

The script tries to decode each .txt file as UTF-8 first.
If that fails, it decodes as CP1251 and rewrites the file in UTF-8.
"""

from __future__ import annotations

import argparse
from pathlib import Path


def convert_cp1251_to_utf8(root: Path) -> tuple[int, int, int]:
    total = 0
    converted = 0
    errors = 0

    for path in root.rglob("*.txt"):
        if not path.is_file():
            continue
        total += 1
        try:
            path.read_text(encoding="utf-8")
            continue
        except UnicodeDecodeError:
            pass
        except OSError:
            errors += 1
            continue

        try:
            text = path.read_text(encoding="cp1251", errors="replace")
            path.write_text(text, encoding="utf-8")
            converted += 1
        except OSError:
            errors += 1

    return total, converted, errors


def main() -> int:
    parser = argparse.ArgumentParser(description="Convert CP1251 .txt files to UTF-8")
    parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parent / "Картотека")
    args = parser.parse_args()

    root = args.root
    if not root.exists():
        raise SystemExit(f"Root path '{root}' not found. Ensure it exists and is accessible.")

    total, converted, errors = convert_cp1251_to_utf8(root)
    print(f"Scanned: {total}, converted: {converted}, errors: {errors}")
    return 0


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