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

"""Upload a document to 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(
    file_path: str = typer.Argument(..., help="Path to the file to upload"),
    name: str = typer.Option(None, "--name", help="Custom name for the document (defaults to filename)"),
    tags: str = typer.Option(None, "--tags", help="Comma-separated list of tags"),
    description: str = typer.Option(None, "--description", help="Description of the document"),
):
    """Upload a document to the document sync server."""
    try:
        # Validate file exists
        path = Path(file_path)
        if not path.exists():
            error = {"error": f"File not found: {file_path}"}
            print(json.dumps(error), file=sys.stderr)
            raise typer.Exit(1)

        # Parse tags from comma-separated string
        parsed_tags = None
        if tags:
            parsed_tags = [tag.strip() for tag in tags.split(",") if tag.strip()]

        # Create client and push document
        config = Config()
        client = DocumentClient(config)

        result = client.push_document(
            file_path=path,
            name=name,
            tags=parsed_tags,
            description=description
        )

        # Output success result as JSON
        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()
