import requests
import settings
import json
from helpers import dates
from helpers.clear import clear
from github import repos

def count(repo='') :
    if repo == '':
        repo = repos.list()

    total_prs = 0
    repo_pr_counts = {}

    clear()

    if ( repo == 'all'):
        # Iterate over the list of repositories
        for repo_name in repos.get():
            # Count issues for the current repository
            pr_count = query_repo(repo_name)
            total_prs += pr_count

            print(f'{repo_name}: {pr_count}')

        # Print the total number of issues across all repositories
        print(f'Total number of Pull Requests created in the last week across all repositories: {total_prs}')
    else:
        # Count issues for the specified repository
        pr_count = query_repo(repo)
        print(f'Number of Pull Requests created in the last week for {repo}: {pr_count}')

    return


def summary(input_date=None):
    total_prs = 0
    repositories = repos.get()
    for repo_name in repositories:
        total_prs += query_repo(repo_name, input_date)

    if not input_date:
        print(f'Pull requests created last week: {total_prs}')
    else:
        print(f'Pull requests created the week of ({input_date}): {total_prs}')
    return


def query_repo(repo_name, input_date=None):
    # Get the date range in ISO format
    previous_monday_iso, recent_sunday_iso = dates.get_iso_date_range(input_date)

    # Define the headers
    headers = {
        'Authorization': f'token {settings.GITHUB_TOKEN}',
        'Accept': 'application/vnd.github.v3+json'
    }

    # Define the API endpoint for each repository
    url = f'https://api.github.com/repos/awesomemotive/{repo_name}/pulls'

    # Define the parameters
    params = {
        'state': 'all',
        'sort': 'created',
        'direction': 'desc'
    }

    # Make the request
    response = requests.get(url, headers=headers, params=params)
    prs = response.json()

    # Filter PRs created in the last week
    recent_prs = [pr for pr in prs if pr['created_at'] >= previous_monday_iso and pr['created_at'] <= recent_sunday_iso]

    return len(recent_prs)
