#!/usr/bin/env python3
"""ASUCB dedash — thin CLI over content_remediation.fix_dashes.

Usage
-----
  python scripts/dedash.py FILE [FILE...]   fix em/en dashes in-place
  python scripts/dedash.py --stdin          fix HTML from stdin -> stdout
  python scripts/dedash.py --check FILE ... exit 1 if any em/en dashes found

Options
-------
  --check   Check mode: exit non-zero if any em/en dash present; no writes.
  --stdin   Read from stdin; write fixed HTML to stdout (mutually exclusive
            with FILE positional args and --check).

Exit codes
----------
  0   Clean (or fixed successfully).
  1   --check mode: em/en dash(es) found.
  2   Error (file not found, etc.).
"""

import argparse
import sys
import os

sys.path.insert(0, os.path.dirname(__file__))
from content_remediation import fix_dashes, _DASH_TOKENS


def _has_dashes(html: str) -> bool:
    return any(html.count(t) > 0 for t in _DASH_TOKENS)


def main():
    parser = argparse.ArgumentParser(
        prog="dedash",
        description="Replace em/en dashes in Canvas HTML files.",
    )
    parser.add_argument(
        "files",
        nargs="*",
        metavar="FILE",
        help="HTML file(s) to process in-place.",
    )
    parser.add_argument(
        "--stdin",
        action="store_true",
        help="Read from stdin and write fixed output to stdout.",
    )
    parser.add_argument(
        "--check",
        action="store_true",
        help="Exit non-zero if any em/en dash found; make no changes.",
    )
    args = parser.parse_args()

    if args.stdin and args.files:
        parser.error("--stdin cannot be combined with positional FILE arguments.")
    if args.stdin and args.check:
        parser.error("--stdin and --check cannot be combined.")
    if not args.files and not args.stdin:
        parser.error("Provide FILE argument(s) or --stdin.")

    if args.stdin:
        html = sys.stdin.read()
        fixed, n = fix_dashes(html)
        sys.stdout.write(fixed)
        print(f"dedash: {n} change(s)", file=sys.stderr)
        return

    found_any = False
    error = False
    for path in args.files:
        try:
            html = open(path, encoding="utf-8").read()
        except OSError as e:
            print(f"dedash: ERROR reading {path}: {e}", file=sys.stderr)
            error = True
            continue

        if args.check:
            if _has_dashes(html):
                found_any = True
                count = sum(html.count(t) for t in _DASH_TOKENS)
                print(f"dedash: {path}: {count} em/en dash(es) found", file=sys.stderr)
            else:
                print(f"dedash: {path}: clean", file=sys.stderr)
        else:
            fixed, n = fix_dashes(html)
            if n:
                try:
                    with open(path, "w", encoding="utf-8") as f:
                        f.write(fixed)
                    print(f"dedash: {path}: {n} change(s), written", file=sys.stderr)
                except OSError as e:
                    print(f"dedash: ERROR writing {path}: {e}", file=sys.stderr)
                    error = True
            else:
                print(f"dedash: {path}: clean (no changes)", file=sys.stderr)

    if error:
        sys.exit(2)
    if args.check and found_any:
        sys.exit(1)


if __name__ == "__main__":
    main()
