import requests
import json
import os
from dotenv import load_dotenv  # Import load_dotenv to read .env file
import sys
from textwrap import dedent

# Load environment variables from .env file
load_dotenv()

# outline API doc: https://www.getoutline.com/developers#tag/documents/POST/documents.create

class API_Client:
    def __init__(self, base_url, api_token):
        # Trim trailing slash from base_url
        self.base_url = base_url.rstrip('/')
        self.api_token = api_token
        self.headers = {
            "Authorization": f"Bearer {self.api_token}",
            "Content-Type": "application/json"
        }

    def call_api(self, http_verb, endpoint, data=None):
        url = self.build_url(endpoint)
        response = requests.request(http_verb, url, headers=self.headers, json=data)

        if response.status_code == 200:
            return response.json()
        else:
            raise Exception(f"API call failed with status code {response.status_code}: {response.text}")

    def build_url(self, endpoint):
        # Trim leading slash from endpoint
        return f"{self.base_url}/{endpoint.lstrip('/')}"

    def api_request(self, http_verb, endpoint, data=None, show_json_dump=True):
        """Common method to handle API requests and error handling."""
        try:
            response_data = self.call_api(http_verb, endpoint, data)
            if show_json_dump:
                formatted_json = json.dumps(response_data, indent=4)
                print("Response:", formatted_json)
            return response_data
        except Exception as e:
            print(f"Failed to make API call to {endpoint}.")
            print("Error:", str(e))
            data_dumped = json.dumps(data, indent=4) if data else "{}"
            print("Data:", data_dumped)
            # Attempt to print the error response if available
            if hasattr(e, 'response') and e.response is not None:
                error_json = json.dumps(e.response.json(), indent=4)
                print("Response:", error_json)

    def create_document(self, title, collection_id, parent_document_id, publish=True, show_json_dump=True):
        # get template content
        data = {
            "title": title,
            "text": dedent(f"""
            # test Sylvain

            {title}

            created by API
            """),
            "collectionId": collection_id,
            "parentDocumentId": parent_document_id,
            "publish": publish,
        }
        response_data = self.api_request("POST", "documents.create", data, show_json_dump)
        # Return the fetched data result from the successful API call
        return response_data

    def create_document(self, title, collection_id, parent_document_id, templateId=None, publish=True, show_json_dump=True):
        # Fetch template content if templateId is provided
        template_content = ""
        if templateId:
            template_data = self.get_document(templateId, show_json_dump=False)
            template_content = template_data['data']['text']

        data = {
            "title": title,
            "text": template_content,
            "collectionId": collection_id,
            "parentDocumentId": parent_document_id,
            "publish": publish,
        }
        response_data = self.api_request("POST", "documents.create", data, show_json_dump)
        # Return the fetched data result from the successful API call
        return response_data

    def get_document(self, document_id, show_json_dump=True):
        """Retrieve a document by its ID using a POST request."""
        data = {
            "id": document_id
        }
        return self.api_request("POST", "documents.info", data, show_json_dump=show_json_dump)


# Read Configuration
env_vars = """
OUTLINE_API_URL_BASE
API_TOKEN
PARENT_PAGE_ID
COLLECTION_ID
TEMPLATE_ID
""".split()

for v in env_vars:
    value = os.getenv(v)
    if not value:
        print(f"Error: '{v}' must be set in the .env file.")
        exit(1)
    globals()[v] = value

# Check if the API token is set
if not API_TOKEN:
    print("Error: API_TOKEN must be set in the .env file.")
    exit(1)

# Create an instance of the APIClient
outline_api_client = API_Client(OUTLINE_API_URL_BASE, API_TOKEN)

# Check command-line arguments
if len(sys.argv) < 2:
    print("Usage: python script.py <NEW_DOCUMENT_TITLE> [--get_document DOC_ID]")
    exit(1)

# Handle the command-line arguments
if sys.argv[1] == '--get_document':
    if len(sys.argv) != 3:
        print("Usage: python script.py --get_document DOC_ID")
        exit(1)

    doc_id = sys.argv[2]
    document_data = outline_api_client.get_document(doc_id)
    # You can process or print the document data as needed
else:
    NEW_DOCUMENT_TITLE = sys.argv[1]
    new_document_data = outline_api_client.create_document(NEW_DOCUMENT_TITLE, COLLECTION_ID, PARENT_PAGE_ID, templateId=TEMPLATE_ID)

    #outline_api_client.update_document(document_data=new_document_data,
    #                                   title=f'Updated Title: {NEW_DOCUMENT_TITLE}',
    #                                   templateId=TEMPLATE_ID,
    #                                   publish=True,
    #)