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

"""Query documents 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(
    name: str = typer.Option(None, "--name", help="Filter by filename pattern"),
    tags: str = typer.Option(None, "--tags", help="Comma-separated list of tags (AND logic)"),
    limit: int = typer.Option(None, "--limit", help="Maximum number of results"),
    include_relations: bool = typer.Option(False, "--include-relations", help="Include document relations in response"),
):
    """Query documents from the document sync server."""
    try:
        # 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 query documents
        config = Config()
        client = DocumentClient(config)

        results = client.query_documents(
            name=name,
            tags=parsed_tags,
            limit=limit,
            include_relations=include_relations
        )

        # Output results as JSON array
        print(json.dumps(results, 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()
