#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "httpx",
#     "typer",
# ]
# ///

"""Download a document from the document sync server."""

import typer
from pathlib import Path
import json
import sys

# Add lib directory to path for imports
sys.path.insert(0, str(Path(__file__).parent / "lib"))
from config import Config
from client import DocumentClient

app = typer.Typer(add_completion=False)


@app.command()
def main(
    document_id: str = typer.Argument(..., help="ID of the document to download"),
    output: str = typer.Option(None, "--output", "-o", help="Output file path (defaults to original filename)"),
):
    """Download a document from the document sync server."""
    try:
        # Create client and pull document
        config = Config()
        client = DocumentClient(config)

        content, filename = client.pull_document(document_id)

        # Determine output path
        output_path = Path(output) if output else Path(filename)

        # Write content to file
        output_path.write_bytes(content)

        # Output success message as JSON
        result = {
            "success": True,
            "document_id": document_id,
            "filename": str(output_path),
            "size_bytes": len(content)
        }
        print(json.dumps(result, indent=2))

    except Exception as e:
        # Output error as JSON to stderr
        error = {"error": str(e)}
        print(json.dumps(error), file=sys.stderr)
        raise typer.Exit(1)


if __name__ == "__main__":
    app()
