import os

import requests
import dotenv

from terminaltables import AsciiTable


def get_vacancy_sample_hh(vacancy):

    hh_api_url = 'https://api.hh.ru/vacancies'
    vacancies_per_page = 100
    vacancy_area = 1

    payload = {
        'text': vacancy,
        'area': vacancy_area,
        'per_page': vacancies_per_page
    }

    response = requests.get(hh_api_url, params=payload)
    response.raise_for_status()
    decoded_response = response.json()
    vacancy_sample = decoded_response['items']
    pages = decoded_response['pages']

    page = 1
    while page < pages:
        payload = {
            'text': vacancy,
            'area': vacancy_area,
            'page': page,
            'per_page': vacancies_per_page
        }

        page_response = requests.get(hh_api_url, params=payload)
        page_response.raise_for_status()
        decoded_page_response = page_response.json()
        vacancy_sample += decoded_page_response['items']
        page += 1

    return vacancy_sample


def get_vacancy_sample_sj(vacancy, client_id, secret_key):

    sj_api_url = 'https://api.superjob.ru/2.0/vacancies/'
    vacancy_area = 4
    vacancy_catalogue = 48

    headers = {
        'client_id': client_id,
        'X-Api-App-Id': secret_key,
    }

    page = 0
    more = True

    vacancy_sample = []

    while more is True:
        payload = {
            'keyword': vacancy,
            'town': vacancy_area,
            'page': page,
            'catalogues': vacancy_catalogue
        }
        page_response = requests.get(sj_api_url, params=payload, headers=headers)
        page_response.raise_for_status()
        decoded_page_response = page_response.json()
        vacancy_sample += decoded_page_response['objects']
        more = decoded_page_response['more']
        page += 1

    return vacancy_sample


def predict_salary(salary_from, salary_to):

    salary_to_ratio = 0.8
    salary_from_ratio = 1.2

    if salary_from is None:
        salary_from = 0
    if salary_to is None:
        salary_to = 0
    if salary_from == 0:
        return salary_to * salary_to_ratio
    elif salary_to == 0:
        return salary_from * salary_from_ratio
    else:
        return (salary_to + salary_from) / 2


def predict_rub_salary_hh(vacancy):
    if vacancy['salary'] is None:
        return None
    try:
        if vacancy['salary']['currency'] != 'RUR':
            return None
    except TypeError:
        return None
    salary_from = vacancy['salary']['from']
    salary_to = vacancy['salary']['to']
    salary = predict_salary(salary_from, salary_to)

    return salary


def predict_rub_salary_sj(vacancy):
    salary_from = vacancy['payment_from']
    salary_to = vacancy['payment_to']
    salary = predict_salary(salary_from, salary_to)

    if salary == 0:
        return None

    return salary


def get_vacancy_statistics(vacancy_title, vacancy_sample, source):
    vacancies_found = len(vacancy_sample)
    vacancies_processed = 0
    amount = 0
    for vacancy in vacancy_sample:
        if source == 'hh':
            salary = predict_rub_salary_hh(vacancy)
        elif source == 'sj':
            salary = predict_rub_salary_sj(vacancy)
        else:
            raise ValueError('Wrong argument "source", argument must be "sj" or "hh" ')

        if salary is None:
            continue
        amount += salary
        vacancies_processed += 1

    try:
        av_salary = int(amount / vacancies_processed)
    except ZeroDivisionError:
        av_salary = 0
    vacancy_stats = {
        vacancy_title: {
            'vacancies_found': vacancies_found,
            'vacancies_processed': vacancies_processed,
            'average_salary': av_salary
        }
    }
    return vacancy_stats


def get_all_vacancies_stats(vacancy_titles, source, client_id='', secret_key=''):
    if source != 'hh' and source != "sj":
        raise ValueError('Wrong argument "source", argument must be "sj" or "hh" ')
    all_vacancies_stats = {}
    for vacancy_title in vacancy_titles:
        if source == 'hh':
            vacancy_sample = get_vacancy_sample_hh(vacancy_title)
        else:
            vacancy_sample = get_vacancy_sample_sj(vacancy_title, client_id, secret_key)
        all_vacancies_stats.update(get_vacancy_statistics(vacancy_title, vacancy_sample, source))
    return all_vacancies_stats


def format_data_for_table(all_vacancies_stats):
    table_data = [["Язык программирования", 'Вакансий найдено', 'Вакансий обработано', 'Средняя зарплата']]
    for key in all_vacancies_stats:
        table_data.append([
            key,
            all_vacancies_stats[key]['vacancies_found'],
            all_vacancies_stats[key]['vacancies_processed'],
            all_vacancies_stats[key]['average_salary'],
        ])
    return table_data


def main():

    vacancy_titles = [
        'javascript',
        'java',
        'python',
        'ruby',
        'php',
        'c++',
        'c#',
        'c',
        'go',
        'objective-c']

    dotenv.load_dotenv()
    sj_client_id = os.getenv('SJ_CLIENT_ID')
    sj_secret_key = os.getenv('SJ_SECRET_KEY')

    hh_vacancies = get_all_vacancies_stats(vacancy_titles, 'hh')
    hh_table_data = format_data_for_table(hh_vacancies)
    hh_table_title = 'HeadHunter Moscow'
    table_instance_hh = AsciiTable(hh_table_data, hh_table_title)
    print(table_instance_hh.table)
    print()

    sj_vacancies = get_all_vacancies_stats(vacancy_titles, 'sj', sj_client_id, sj_secret_key)
    sj_table_data = format_data_for_table(sj_vacancies)
    sj_table_title = 'SuperJob Moscow'
    table_instance_sj = AsciiTable(sj_table_data, sj_table_title)
    print(table_instance_sj.table)
    print()


if __name__ == '__main__':
    main()

import os

import requests
import dotenv

from terminaltables import AsciiTable


def get_vacancy_sample_hh(vacancy):

    hh_api_url = 'https://api.hh.ru/vacancies'
    vacancies_per_page = 100
    vacancy_area = 1

    payload = {
        'text': vacancy,
        'area': vacancy_area,
        'per_page': vacancies_per_page
    }

    response = requests.get(hh_api_url, params=payload)
    response.raise_for_status()
    decoded_response = response.json()
    vacancy_sample = decoded_response['items']
    pages = decoded_response['pages']

    page = 1
    while page < pages:
        payload = {
            'text': vacancy,
            'area': vacancy_area,
            'page': page,
            'per_page': vacancies_per_page
        }

        page_response = requests.get(hh_api_url, params=payload)
        page_response.raise_for_status()
        decoded_page_response = page_response.json()
        vacancy_sample += decoded_page_response['items']
        page += 1

    return vacancy_sample


def get_vacancy_sample_sj(vacancy, client_id, secret_key):

    sj_api_url = 'https://api.superjob.ru/2.0/vacancies/'
    vacancy_area = 4
    vacancy_catalogue = 48

    headers = {
        'client_id': client_id,
        'X-Api-App-Id': secret_key,
    }

    page = 0
    more = True

    vacancy_sample = []

    while more is True:
        payload = {
            'keyword': vacancy,
            'town': vacancy_area,
            'page': page,
            'catalogues': vacancy_catalogue
        }
        page_response = requests.get(sj_api_url, params=payload, headers=headers)
        page_response.raise_for_status()
        decoded_page_response = page_response.json()
        vacancy_sample += decoded_page_response['objects']
        more = decoded_page_response['more']
        page += 1

    return vacancy_sample


def predict_salary(salary_from, salary_to):

    salary_to_ratio = 0.8
    salary_from_ratio = 1.2

    if salary_from is None:
        salary_from = 0
    if salary_to is None:
        salary_to = 0
    if salary_from == 0:
        return salary_to * salary_to_ratio
    elif salary_to == 0:
        return salary_from * salary_from_ratio
    else:
        return (salary_to + salary_from) / 2


def predict_rub_salary_hh(vacancy):
    if vacancy['salary'] is None:
        return None
    try:
        if vacancy['salary']['currency'] != 'RUR':
            return None
    except TypeError:
        return None
    salary_from = vacancy['salary']['from']
    salary_to = vacancy['salary']['to']
    salary = predict_salary(salary_from, salary_to)

    return salary


def predict_rub_salary_sj(vacancy):
    salary_from = vacancy['payment_from']
    salary_to = vacancy['payment_to']
    salary = predict_salary(salary_from, salary_to)

    if salary == 0:
        return None

    return salary


def get_vacancy_statistics(vacancy_title, vacancy_sample, source):
    vacancies_found = len(vacancy_sample)
    vacancies_processed = 0
    amount = 0
    for vacancy in vacancy_sample:
        if source == 'hh':
            salary = predict_rub_salary_hh(vacancy)
        elif source == 'sj':
            salary = predict_rub_salary_sj(vacancy)
        else:
            raise ValueError('Wrong argument "source", argument must be "sj" or "hh" ')

        if salary is None:
            continue
        amount += salary
        vacancies_processed += 1

    try:
        av_salary = int(amount / vacancies_processed)
    except ZeroDivisionError:
        av_salary = 0
    vacancy_stats = {
        vacancy_title: {
            'vacancies_found': vacancies_found,
            'vacancies_processed': vacancies_processed,
            'average_salary': av_salary
        }
    }
    return vacancy_stats


def get_all_vacancies_stats(vacancy_titles, source, client_id='', secret_key=''):
    if source != 'hh' and source != "sj":
        raise ValueError('Wrong argument "source", argument must be "sj" or "hh" ')
    all_vacancies_stats = {}
    for vacancy_title in vacancy_titles:
        if source == 'hh':
            vacancy_sample = get_vacancy_sample_hh(vacancy_title)
        else:
            vacancy_sample = get_vacancy_sample_sj(vacancy_title, client_id, secret_key)
        all_vacancies_stats.update(get_vacancy_statistics(vacancy_title, vacancy_sample, source))
    return all_vacancies_stats


def format_data_for_table(all_vacancies_stats):
    table_data = [["Язык программирования", 'Вакансий найдено', 'Вакансий обработано', 'Средняя зарплата']]
    for key in all_vacancies_stats:
        table_data.append([
            key,
            all_vacancies_stats[key]['vacancies_found'],
            all_vacancies_stats[key]['vacancies_processed'],
            all_vacancies_stats[key]['average_salary'],
        ])
    return table_data


def main():

    vacancy_titles = [
        'javascript',
        'java',
        'python',
        'ruby',
        'php',
        'c++',
        'c#',
        'c',
        'go',
        'objective-c']

    dotenv.load_dotenv()
    sj_client_id = os.getenv('SJ_CLIENT_ID')
    sj_secret_key = os.getenv('SJ_SECRET_KEY')

    hh_vacancies = get_all_vacancies_stats(vacancy_titles, 'hh')
    hh_table_data = format_data_for_table(hh_vacancies)
    hh_table_title = 'HeadHunter Moscow'
    table_instance_hh = AsciiTable(hh_table_data, hh_table_title)
    print(table_instance_hh.table)
    print()

    sj_vacancies = get_all_vacancies_stats(vacancy_titles, 'sj', sj_client_id, sj_secret_key)
    sj_table_data = format_data_for_table(sj_vacancies)
    sj_table_title = 'SuperJob Moscow'
    table_instance_sj = AsciiTable(sj_table_data, sj_table_title)
    print(table_instance_sj.table)
    print()


if __name__ == '__main__':
    main()
