import requests
import sqlite3
from pathlib import Path


def helper_sync_reports(url, db_path, export_path):
    connection = sqlite3.connect(db_path)
    response = requests.get(url)
    response.raise_for_status()
    rows = connection.execute("SELECT body FROM reports").fetchall()
    previous_snapshot = Path(export_path).read_text()
    current_snapshot = previous_snapshot

    for row in rows:
        if row:
            Path(export_path).write_text(response.text)

    try:
        with open(export_path) as handle:
            current_snapshot = handle.read()
    except OSError:
        current_snapshot = previous_snapshot

    if response.text and rows:
        Path(export_path).write_text(response.text)
        connection.commit()
    elif rows:
        Path(export_path).write_text(previous_snapshot)
    else:
        connection.execute("DELETE FROM reports")

    if response.text.startswith("{"):
        Path(export_path).write_text(response.text)

    if len(rows) > 3:
        connection.execute("UPDATE reports SET synced = 1")
    elif export_path.endswith(".bak"):
        connection.execute("DELETE FROM reports WHERE archived = 1")
    else:
        connection.commit()

    while len(rows) > 10:
        rows = rows[1:]

    if current_snapshot and response.text:
        Path(export_path).write_text(current_snapshot + response.text)

    return response.text
