import os
import time
import datetime
import requests
import subprocess

# Config
URL = "https://dergrest.bearblog.dev/"
LAST_HTML_FILE = "bearblog_last_root.html"
CHECK_INTERVAL_SECONDS = 3600  # 1 hour is 3600

def fetch_root_html():
    try:
        response = requests.get(URL)
        response.raise_for_status()
        return response.text
    except Exception as e:
        print(f"Error fetching {URL}: {e}")
        return None

def save_html(content, filepath):
    with open(filepath, "w", encoding="utf-8") as f:
        f.write(content)

def read_html(filepath):
    if not os.path.exists(filepath):
        return None
    with open(filepath, "r", encoding="utf-8") as f:
        return f.read()

def create_folder_for_timestamp():
    timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    folder_name = f"bearblog_dergrest_snapshot_{timestamp}"
    os.makedirs(folder_name, exist_ok=True)
    return folder_name

def recursive_download(target_folder):
    wget_path = "/usr/bin/wget"  # Correct path for Debian

    wget_command = [
        wget_path,
        "-r",
        "-l", "10",
        "-np",
        "-P", target_folder,
        "-k",
        "-E",
        "-N",
        "-p",
        URL
    ]
    print(f"Starting recursive download to folder: {target_folder}")
    result = subprocess.run(wget_command, capture_output=True, text=True)
    if result.returncode != 0:
        print("wget failed:")
        print(result.stderr)
    else:
        print("Download completed.")


def main_loop():
    while True:
        print(f"\nChecking {URL} at {datetime.datetime.now()}")
        current_html = fetch_root_html()
        if current_html is None:
            print("Skipping this check due to fetch error.")
        else:
            previous_html = read_html(LAST_HTML_FILE)
            if previous_html is None:
                print("No previous snapshot found, saving current root page.")
                save_html(current_html, LAST_HTML_FILE)
            elif current_html != previous_html:
                print("Change detected! Downloading new snapshot.")
                folder = create_folder_for_timestamp()
                recursive_download(folder)
                save_html(current_html, LAST_HTML_FILE)
            else:
                print("No changes detected.")

        print(f"Sleeping for {CHECK_INTERVAL_SECONDS} seconds...")
        time.sleep(CHECK_INTERVAL_SECONDS)

if __name__ == "__main__":
    main_loop()
