import os
import sys
import json
import requests
from dotenv import load_dotenv


load_dotenv()

argv = sys.argv[1:]

usage = """\
'Usage:

        python wpcom_priv_get_posts.py <site>'

site: A valid wordpress.com site.
"""

if len(argv) == 0 or not argv[0]:
    print(usage)
    exit(1)

site = argv[0]

access_token_url = 'https://public-api.wordpress.com/oauth2/token'

data = {
    'client_id': os.getenv('WPCOM_APP_CLIENT_ID'),
    'client_secret': os.getenv('WPCOM_APP_CLIENT_SECRET'),
    'grant_type': 'password',
    'username': os.getenv('WPCOM_APP_USERNAME'),
    'password': os.getenv('WPCOM_APP_PASSWORD'),
}

response = requests.post(access_token_url, data=data)

if response.status_code != 200:
    raise ValueError('failed authenticating')

auth_data = response.json()
access_token = auth_data['access_token']

posts_endpoint = f'https://public-api.wordpress.com/rest/v1.1/sites/{site}/posts'

headers = {
    'authorization': f'Bearer {access_token}'
}

response = requests.get(posts_endpoint, headers=headers)

if response.status_code != 200:
    print(f'HTTP Request failed with status {response.status_code}' )
    exit(1)

response_data = response.json()
post_count = len(response_data['posts'])

print(f'got {post_count} posts.')
