#!/usr/bin/env python3
"""Correct Persian files in place: python3 /path/to/ghazal-persian/fix.py FILE [FILE...].
With no files, read stdin, write corrected text to stdout and findings to stderr.
GHAZAL_KEY holds the API key. Files above the key's request limit are sent in parts.
"""
import argparse
import json
import os
import re
import sys
import time
import urllib.error
import urllib.request

URL = os.environ.get("GHAZAL_URL", "https://ghazalai.ir").rstrip("/") + "/api/v1/fix"
MOST = 20000
KEY = os.environ.get("GHAZAL_KEY", "").strip()
if not KEY:
    sys.exit("Set GHAZAL_KEY to a free key made after signing in at https://ghazalai.ir/account/.")


def fix(text, form, **options):
    body = json.dumps({"text": text, "format": form, "offsets": "codepoint", **options}).encode()
    headers = {"content-type": "application/json", "authorization": "Bearer " + KEY}
    for _ in range(4):
        try:
            with urllib.request.urlopen(urllib.request.Request(URL, body, headers), timeout=60) as answer:
                return json.load(answer)
        except urllib.error.HTTPError as e:
            wait = int(e.headers.get("retry-after") or 2)
            if e.code not in (429, 503) or wait > 30:
                try:
                    error = json.load(e)["error"]
                    if error.get("code") == "too_long" and len(text) > MOST:
                        return None
                    sys.exit(error["message"])
                except (ValueError, KeyError, TypeError):
                    sys.exit(f"Ghazal answered {e.code}")
            time.sleep(wait)
        except urllib.error.URLError:
            sys.exit("Could not reach Ghazal")
    sys.exit("Ghazal is busy; try again later")


def parts(text):
    if len(text) <= MOST:
        return [text]
    out = [""]
    for p in text.split("\n\n"):
        if len(p) > MOST:
            sys.exit("a paragraph is longer than 20,000 characters")
        if len(out[-1]) + len(p) + 2 > MOST:
            out.append("")
        out[-1] += ("\n\n" if out[-1] else "") + p
    return out


def document(text, form, **options):
    done, start = [], 0
    while True:
        answer = fix(text, form, **options, **({"from": start} if start else {}))
        if answer is None:
            done = [fix(part, form, **options) for part in parts(text)]
            for part in done[:-1]:
                part["text"] += "\n\n"
            return done
        end = answer.get("checked_to", len(text))
        if type(end) is not int or not (start < end <= len(text) or not text and end == 0):
            sys.exit("Ghazal returned an invalid checked_to offset.")
        done.append(answer)
        if end == len(text):
            return done
        start = end


def findings(done, stream, decisions=False):
    for d in done:
        for f in d["left"]:
            if not decisions or f["severity"] in ("advice", "guess") or f["rule"].startswith("spell."):
                print(f'{f["severity"]}\t{f["rule"]}\t{f["text"]} -> {" | ".join(f["suggestions"])}', file=stream)


def house(value):
    allowed = {"ezafe": ("ye", "hamza"), "digits": ("persian", "latin", "keep"), "quotes": ("guillemets", "keep")}
    out = {}
    for part in value.split(","):
        key, sep, choice = part.partition("=")
        if not sep or key not in allowed or choice not in allowed[key] or key in out:
            raise argparse.ArgumentTypeError("Use ezafe=ye|hamza,digits=persian|latin|keep,quotes=guillemets|keep; send each key once.")
        out[key] = choice
    return out


def words_file(path):
    words = []
    try:
        with open(path, encoding="utf-8") as source:
            while line := source.readline(64):
                word = line.rstrip("\r\n")
                if not word:
                    continue
                if len(word) > 60 or not re.fullmatch(r"(?:[^\W_]|[ً-ٰٟـ])+(?:‌(?:[^\W_]|[ً-ٰٟـ])+)*", word):
                    raise argparse.ArgumentTypeError("Each line must contain one word of at most 60 characters, without spaces.")
                words.append(word)
                if len(words) > 500:
                    raise argparse.ArgumentTypeError("The word list must contain at most 500 entries.")
    except (OSError, UnicodeError):
        raise argparse.ArgumentTypeError("Could not read the word list as UTF-8.")
    return words


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("files", nargs="*")
    parser.add_argument("--text", action="store_true", help="Treat all input as plain text")
    parser.add_argument("--style", choices=("ghazal", "academy"))
    parser.add_argument("--house", type=house, help="Writing preferences, for example ezafe=hamza,digits=latin,quotes=keep")
    parser.add_argument("--words", type=words_file, metavar="FILE", help="Personal words, one word per line (UTF-8); at most 500 words of at most 60 characters")
    parser.add_argument("--kind", choices=("formal", "colloquial"))
    parser.add_argument("--profile", choices=("llm",), help="Use the rules reviewed on Persian written by language models")
    parser.add_argument("--sure-only", action="store_true", help="Leave style suggestions unapplied")
    args = parser.parse_args()
    options = {k: v for k in ("style", "kind", "house", "profile") if (v := getattr(args, k))}
    if args.words is not None:
        options["words"] = args.words
    if not args.files:
        done = document(sys.stdin.read(), "text" if args.text else "markdown", **options)
        sys.stdout.write("".join(d["text"] for d in done))
        findings(done, sys.stderr)
        return
    options.update(apply="sure" if args.sure_only else "house")
    for path in args.files:
        try:
            with open(path, encoding="utf-8", newline="") as source:
                text = source.read()
            form = "text" if args.text or path.lower().endswith(".txt") else "markdown"
            done = document(text, form, **options)
            with open(path, "w", encoding="utf-8", newline="") as target:
                target.write("".join(d["text"] for d in done))
        except OSError as e:
            sys.exit(f"{path}: {e.strerror}")
        count = sum(len(d["applied"]) for d in done)
        print(f"{path}: {count} change{'s' if count != 1 else ''}")
        findings(done, sys.stdout, decisions=True)
        print(f"{path}: Done.")


if __name__ == "__main__":
    main()
