import os
import uuid
from dotenv import load_dotenv
load_dotenv()

from authorization_code_client import authorization_code_flow

BASE_URL = os.getenv('BASE_URL')

auth_response = authorization_code_flow()

from reod.reod_client import AuthenticatedClient

with AuthenticatedClient(
    base_url=BASE_URL,
    token=auth_response.access_token
) as client:
    from reod.reod_client.models import ListUserContextResponse200
    from reod.reod_client.api.user_context import list_user_context
    from reod.reod_client.types import Response

    # Find the user context created by example_create_context
    ctx_external_ref = '0ac33437-96fd-419d-871c-50c92f40fbb6'

    ctx_id: str = None
    list_response: Response[ListUserContextResponse200] = list_user_context.sync_detailed(client=client, size=1000)
    if list_response.status_code != 200:
        print(f"Error ({list_response.status_code}): {list_response.content.decode('utf-8')}")
        exit (1)

    for ctx in list_response.parsed.data:
        if ctx.additional_properties["externalRef"] == ctx_external_ref:
            ctx_id = ctx.additional_properties["id"]

    if ctx_id is None:
        print(f"No context with external reference {ctx_external_ref} found")
        exit (1)

    # List all files

    from reod.reod_client.models import GetAllFilesResponse200, FileGetDescription
    from reod.reod_client.api.file_manager import get_all_files, get_file_description_by_id
    from reod.reod_client.types import Response

    list_files_response: Response[GetAllFilesResponse200] = get_all_files.sync_detailed(client=client, size=1000, user_context=uuid.UUID(ctx_id))
    if list_files_response.status_code != 200:
        print(f"Error {list_files_response.status_code}: {list_files_response.content.decode("utf-8")}")
        exit (1)

    files = list_files_response.parsed.data
    print (f"Found {len(files)} files.")
    for file in files:
        print (f"File: {file}")

        get_file_response: Response[FileGetDescription] = get_file_description_by_id.sync_detailed(client=client, user_context=uuid.UUID(ctx_id), file_id=uuid.UUID(str(file.additional_properties['id'])))
        if get_file_response.status_code != 200:
            print(f"Error {get_file_response.status_code}: {get_file_response.content.decode("utf-8")}")
            exit (1)

        print (f"Description: {get_file_response.parsed}")

