import argparse
import json
import sys

from .client import embed


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="wsi-embed",
        description="Upload a WSI slide and save embedding JSON locally.",
    )
    parser.add_argument("slide_path", help="Path to local WSI slide file")
    parser.add_argument("--model", required=True, help="Model id (example: uni-v1)")
    parser.add_argument("--key", required=True, help="User API key")
    parser.add_argument(
        "--server-url",
        default="http://127.0.0.1:8000",
        help="Backend URL (default: http://127.0.0.1:8000)",
    )
    parser.add_argument(
        "--output-dir",
        default=None,
        help="Directory to save embedding JSON (default: ./embeddings)",
    )
    parser.add_argument(
        "--timeout-seconds",
        type=int,
        default=300,
        help="HTTP timeout in seconds (default: 300)",
    )
    parser.add_argument(
        "--print-json",
        action="store_true",
        help="Print full JSON result to stdout",
    )
    return parser


def main() -> int:
    parser = build_parser()
    args = parser.parse_args()

    try:
        result = embed(
            slide_path=args.slide_path,
            model=args.model,
            key=args.key,
            server_url=args.server_url,
            output_dir=args.output_dir,
            timeout_seconds=args.timeout_seconds,
        )
    except Exception as exc:  # noqa: BLE001
        print("Error:", str(exc), file=sys.stderr)
        return 1

    print("Embedding ID:", result["embedding_id"])
    print("Saved path:", result["saved_path"])
    print("Model:", result["model"])
    print("Vector length:", len(result.get("embedding", [])))
    if args.print_json:
        print(json.dumps(result, indent=2))
    return 0


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