import os
import requests
import datetime

REPO_NAME = "DSpace Filatov"

# Указываем начальный год и месяц
start_year = 2025
start_month = 1

# Получаем текущую дату
current_date = datetime.datetime.now()
end_year = current_date.year
end_month = current_date.month

month_names = {
    1: 'Січень', 2: 'Лютий', 3: 'Березень', 4: 'Квітень',
    5: 'Травень', 6: 'Червень', 7: 'Липень', 8: 'Серпень',
    9: 'Вересень', 10: 'Жовтень', 11: 'Листопад', 12: 'Грудень'
}

def get_downloads(start_datetime, end_datetime):
    """ Выполнить запрос к Solr и получить количество загрузок """
    solr_url = "http://localhost:8983/solr/statistics/select"
    params = {
        'fq': [
            'bundleName:ORIGINAL',
            'isBot:false',
            'statistics_type:view',
            f'time:[{start_datetime} TO {end_datetime}]'
        ],
        'q': 'type:0',
        'indent': 'true',
        'rows': '0',
        'q.op': 'AND'
    }

    try:
        response = requests.get(solr_url, params=params)
        response.raise_for_status()
        data = response.json()
        return data['response']['numFound']
    except (requests.RequestException, KeyError) as e:
        print(f"Ошибка при запросе Solr: {e}")
        return 0

def get_submitted_documents(start_datetime, end_datetime):
    """ Выполнить запрос к Solr и получить количество отправленных документов """
    solr_url = "http://localhost:8983/solr/search/select"
    params = {
        'fq': [
            '-entityType: Person',
            'discoverable:true',
            'withdrawn:false',
            f'dc.date.accessioned_dt:[{start_datetime} TO {end_datetime}]'
        ],
        'q': 'archived:true',
        'indent': 'true',
        'rows': '0',
        'q.op': 'AND'
    }

    try:
        response = requests.get(solr_url, params=params)
        response.raise_for_status()
        data = response.json()
        return data['response']['numFound']
    except (requests.RequestException, KeyError) as e:
        print(f"Ошибка при запросе Solr: {e}")
        return 0

def get_views(start_datetime, end_datetime):
    """ Выполнить запрос к Solr и получить количество просмотров документов """
    solr_url = "http://localhost:8983/solr/statistics/select"
    params = {
        'fq': [
            'isBot:false',
            'statistics_type:view',
            f'time:[{start_datetime} TO {end_datetime}]'
        ],
        'q': 'type:2',
        'indent': 'true',
        'rows': '0',
        'q.op': 'AND'
    }

    try:
        response = requests.get(solr_url, params=params)
        response.raise_for_status()
        data = response.json()
        return data['response']['numFound']
    except (requests.RequestException, KeyError) as e:
        print(f"Ошибка при запросе Solr: {e}")
        return 0

def generate_daily_report(year, month, month_name):
    """ Генерируем подотчет по дням """
    reports_dir = 'reports'
    if not os.path.exists(reports_dir):
        os.makedirs(reports_dir)

    days_in_month = (datetime.date(year, month, 1) + datetime.timedelta(days=32)).replace(day=1) - datetime.timedelta(days=1)
    daily_data = []

    for day in range(1, days_in_month.day + 1):
        start_datetime = f"{year}-{str(month).zfill(2)}-{str(day).zfill(2)}T00:00:00Z"
        end_datetime = f"{year}-{str(month).zfill(2)}-{str(day).zfill(2)}T23:59:59Z"
        downloads = get_downloads(start_datetime, end_datetime)
        submitted_docs = get_submitted_documents(start_datetime, end_datetime)
        views = get_views(start_datetime, end_datetime)
        daily_data.append({'day': day, 'downloads': downloads, 'submitted_docs': submitted_docs, 'views': views})

    output_file = f"{reports_dir}/{year}-{str(month).zfill(2)}.html"
    with open(output_file, 'w', encoding='utf-8') as file:
        html = f"""
<!DOCTYPE html>
<html lang="uk">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Статистика за {month_name} {year}</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <h1 class="mt-4">Статистика за {month_name} {year}</h1>
        <table class="table table-bordered mt-4">
            <thead>
                <tr>
                    <th>День</th>
                    <th><a href="../submitters.html">Кількість відправлених документів</a></th>
                    <th>Кількість переглядів</th>
                    <th>Кількість завантажень файлів</th>
                </tr>
            </thead>
            <tbody>
"""
        for row in daily_data:
            html += f"<tr><td>{row['day']}</td><td>{row['submitted_docs']}</td><td>{row['views']}</td><td>{row['downloads']}</td></tr>"

        html += """
            </tbody>
        </table>
        <a href="../statistics.html" class="btn btn-primary mt-4">Назад до помісячної статистики</a>
    </div>
</body>
</html>
"""
        file.write(html)

def generate_monthly_report():
    """ Генерируем помесячный отчет """
    data = []

    for year in range(start_year, end_year + 1):
        for month in range(1, 13):
            if year == start_year and month < start_month:
                continue
            if year == end_year and month > end_month:
                break

            start_datetime = f"{year}-{str(month).zfill(2)}-01T00:00:00Z"
            end_datetime = (datetime.date(year, month, 1) + datetime.timedelta(days=32)).replace(day=1) - datetime.timedelta(days=1)
            end_datetime = f"{end_datetime}T23:59:59Z"
            downloads = get_downloads(start_datetime, end_datetime)
            submitted_docs = get_submitted_documents(start_datetime, end_datetime)
            views = get_views(start_datetime, end_datetime)
            data.append({
                'year': year,
                'month': month,
                'month_name': month_names[month],
                'downloads': downloads,
                'submitted_docs': submitted_docs,
                'views': views
            })

            generate_daily_report(year, month, month_names[month])

    with open('statistics.html', 'w', encoding='utf-8') as file:
        html = f"""
<!DOCTYPE html>
<html lang="uk">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cтатистика завантажень {REPO_NAME}</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <h1 class="mt-4">Статистика завантажень {REPO_NAME} на {current_date.strftime('%d.%m.%Y')}</h1>
        <table class="table table-bordered mt-4">
            <thead>
                <tr>
                    <th>Місяць</th>
                    <th><a href="submitters.html">Кількість відправлених документів</a></th>
                    <th>Кількість переглядів</th>
                    <th>Кількість завантажень файлів</th>
                </tr>
            </thead>
            <tbody>
"""
        for row in data:
            html += f"<tr><td><a href='reports/{row['year']}-{str(row['month']).zfill(2)}.html'>{row['month_name']} {row['year']}</a></td><td>{row['submitted_docs']}</td><td>{row['views']}</td><td>{row['downloads']}</td></tr>"

        html += """
            </tbody>
        </table>
        <a href="repository_info.html" class="btn btn-primary mt-4">Перейти до загаального звіту</a>
    </div>
</body>
</html>
"""
        file.write(html)

if __name__ == "__main__":
    generate_monthly_report()
    print("Статичний HTML файл 'statistics.html' успішно створено.")
