from __future__ import annotations

import argparse
import sys
from pathlib import Path

from .core import stamp_file, verify_file


def _build_parser() -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(
        prog="hashstamp",
        description="Stamp files with content hashes and verify integrity via filename-embedded digests.",
    )
    sub = p.add_subparsers(dest="cmd", required=True)

    s = sub.add_parser("stamp", help="Compute a digest and produce a stamped filename (optionally copy/rename).")
    s.add_argument("file", type=Path, help="Path to the file to stamp.")
    s.add_argument("--alg", default="sha256", help="Hash algorithm (default: sha256).")
    s.add_argument("--out", type=Path, default=None, help="Output directory (for --copy or --rename).")
    s.add_argument("--copy", action="store_true", help="Copy file to stamped filename.")
    s.add_argument("--rename", action="store_true", help="Rename/move file to stamped filename.")
    s.add_argument("--overwrite", action="store_true", help="Allow overwriting target if it exists.")
    s.add_argument("--print-path", action="store_true", help="Print the full target path instead of just the filename.")

    v = sub.add_parser("verify", help="Verify the digest embedded in the filename matches file contents.")
    v.add_argument("file", type=Path, help="Path to a stamped file.")
    return p


def main(argv: list[str] | None = None) -> int:
    parser = _build_parser()
    args = parser.parse_args(argv)

    try:
        if args.cmd == "stamp":
            res = stamp_file(
                args.file,
                algorithm=args.alg,
                out_dir=args.out,
                copy=args.copy,
                rename=args.rename,
                overwrite=args.overwrite,
            )
            if args.print_path:
                print(str(res.stamped_path))
            else:
                print(res.stamped_name)
            return 0

        if args.cmd == "verify":
            ok = verify_file(args.file)
            if ok:
                print("OK")
                return 0
            print("MISMATCH")
            return 2

        parser.error("Unknown command")
        return 2

    except Exception as e:
        print(f"error: {e}", file=sys.stderr)
        return 1


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