import os
import requests
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, UploadRequest, UploadRequestMimeType, \
        UploadDescription
    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)

    # Register file upload

    from reod.reod_client.api.file_manager import post_file
    from reod.reod_client.types import Response

    upload_request = UploadRequest(file_name="User-Guide.md", mime_type=UploadRequestMimeType.TEXTPLAIN)

    upload_request_response: Response[UploadDescription] = post_file.sync_detailed(client=client,
                                                                                   user_context=uuid.UUID(ctx_id),
                                                                                   body=upload_request)
    if upload_request_response.status_code != 201:
        print(f"Error {upload_request_response.status_code}: {upload_request_response.content.decode("utf-8")}")
        exit(1)

    upload_description = upload_request_response.parsed
    url = upload_description.put_url
    headers = upload_description.upload_request_headers.to_dict()
    print(f"Upload Description: {upload_description}")

    with open("User-Guide.md", "rb") as file:
        # Upload the file to the given URL with the specified headers
        response = requests.put(url, data=file, headers=headers)

    # Check the response status code
    if response.status_code == 200:
        print("File uploaded successfully.")
    else:
        print(f"Error {response.status_code}: {response.text}")
        exit(1)
