#!/usr/bin/env python3
"""Pre-flight linter. Checks a draft before it is sent, with the Stop hook's own rules.

Reads the draft on stdin or from a file argument. Prints violations and exits 1.
Pass --json for the machine-readable verdict, which the pi extension consumes.
"""

import json
import pathlib
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))

import ste_rules


def main():
    args = [a for a in sys.argv[1:] if not a.startswith("-")]
    flags = {a for a in sys.argv[1:] if a.startswith("-")}

    text = pathlib.Path(args[0]).read_text() if args else sys.stdin.read()

    profile = ste_rules.load_profile()

    if "--fix" in flags:
        fixed, handled, remaining = ste_rules.autofix(profile, text)

        if args:
            pathlib.Path(args[0]).write_text(fixed)
        else:
            sys.stdout.write(fixed)

        for note in handled:
            print(f"  fixed: {note}", file=sys.stderr)

        for hit in remaining:
            print(f"  manual: {hit}", file=sys.stderr)

        return 1 if remaining else 0

    result = ste_rules.verdict(profile, text)

    if "--json" in flags:
        print(json.dumps(result))
        return 0

    # The human report ignores the soft threshold, because a person wants every hint.
    hits = result["hard"] + result["soft"]

    if not hits:
        print(f"clean — {result['words']} words, profile {result['profile']}")
        return 0

    for hit in hits:
        print(f"  - {hit}")

    return 1


if __name__ == "__main__":
    sys.exit(main())
