"""Recipe "search": documents of one class modified in the last N days, newest first.

Usage: python recipes/search.py [class ID, default 1 "Other Document"] [days, default 30]
[limit, default 10]
"""

import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from mfiles_client import run  # noqa: E402
from mfiles_values import (is_not_deleted, is_object_type, lookup,  # noqa: E402
                           property_condition, timestamp)
from recipe_helpers import connect, describe, int_arg  # noqa: E402

from mfiles import IRPCSearch_pb2, IRPCSearch_pb2_grpc  # noqa: E402
from mfiles import enums_pb2 as enums  # noqa: E402
from mfiles import structs_pb2 as structs  # noqa: E402


def main() -> None:
    class_id = int_arg(0, 1)
    days = int_arg(1, 30)
    limit = int_arg(2, 10)
    with connect() as client:
        # [START search]
        since = datetime.now(timezone.utc) - timedelta(days=days)
        request = IRPCSearch_pb2.SearchObjectsRequest(
            # One array: all its conditions must match.
            conditions=[structs.SearchConditionArray(value=[
                is_object_type(0),  # documents
                is_not_deleted(),
                # Property 100 "Class" is a lookup into value list 1, the classes.
                property_condition(100, enums.CONDITION_TYPE_EQUAL, lookup(1, class_id)),
                # Property 21 "Last modified" is a timestamp.
                property_condition(21, enums.CONDITION_TYPE_GREATER_THAN_OR_EQUAL,
                                   timestamp(since)),
            ])],
            # Newest first. The server sorts all matches, then returns the first `limit`.
            sorting=structs.SearchResultsSorting(rules=structs.SortRuleValueArray(values=[
                structs.SortRule(key=21, options=enums.SortRuleFlags(sort_descending=True))])),
            limit=limit)

        search = client.stub(IRPCSearch_pb2_grpc.IRPCSearchStub)
        response = search.SearchObjects(request)
        # [END search]

        more = f" (limited to {limit}; more exist)" if response.has_more_results else ""
        print(f"Documents of class {class_id} modified since {since:%Y-%m-%d}: "
              f"{len(response.results)}{more}")
        for item in response.results:
            print("  " + describe(item.object))


if __name__ == "__main__":
    run(main)
