import json
from datetime import datetime, timedelta
import os

# Configuration Paths
JSON_PATH = '/var/www/billing-control/clients.json'
LOCKOUT_TEMPLATE = '/var/www/billing-control/payment_due.html'
BASE_WWW_PATH = '/var/www'

def update_billing():
    try:
        with open(JSON_PATH) as f:
            clients = json.load(f)
    except FileNotFoundError:
        print(f"Error: {JSON_PATH} not found.")
        return

    now = datetime.now().date()

    for c in clients:
        folder = c.get('folder_name')
        if not folder:
            print("Skipping entry: No folder_name defined.")
            continue

        # Paths for this specific site
        site_path = os.path.join(BASE_WWW_PATH, folder)
        base_index = os.path.join(site_path, "index.html")
        billing_index = os.path.join(site_path, "index.billing.html")
        
        # Verify the folder exists before proceeding
        if not os.path.exists(site_path):
            print(f"[{folder}] Error: Folder not found in {BASE_WWW_PATH}")
            continue

        # Parse Dates
        remind_dt = datetime.strptime(c['remind_start'], "%Y-%m-%d").date()
        lockout_dt = datetime.strptime(c['lockout_start'], "%Y-%m-%d").date()
        pay_due_date = (lockout_dt - timedelta(days=1)).strftime("%d %b %Y")

        # CASE 1: LOCKOUT STATE (Manual or Date-based)
        if c.get('manual_lock') or now >= lockout_dt:
            try:
                with open(LOCKOUT_TEMPLATE, 'r') as f:
                    content = f.read()
                with open(billing_index, 'w') as f:
                    f.write(content)
                print(f"[{folder}] Status: LOCKED")
            except Exception as e:
                print(f"[{folder}] Error writing lockout file: {e}")

        # CASE 2: REMINDER STATE
        elif now >= remind_dt:
            if not os.path.exists(base_index):
                continue
                
            with open(base_index, 'r') as f:
                content = f.read()

            # We use a wrapper div with 'pointer-events: none' to ensure 
            # it doesn't interfere with the website's clicks.
            reminder_html = f'''
            <style>
                #hosting-reminder-wrap {{
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    z-index: 2147483647 !important;
                    pointer-events: none;
                }}
                .hosting-reminder-bar {{
                    background: #ff9800 !important;
                    color: white !important;
                    text-align: center;
                    padding: 12px;
                    font-weight: bold;
                    font-family: sans-serif;
                    font-size: 14px;
                    pointer-events: auto;
                    box-shadow: 0 2px 5px rgba(0,0,0,0.2);
                }}
                /* Push the Angular app down so it doesn't hide behind the bar */
                body {{ padding-top: 45px !important; }}
            </style>
            <div id="hosting-reminder-wrap">
                <div class="hosting-reminder-bar">
                    ⚠️ NOTICE: Hosting payment due by {pay_due_date}. Please settle your invoice.
                </div>
            </div>
            '''
            
            # Injection: Insert immediately after the opening <body> tag
            import re
            # This regex captures <body ...> even if it has classes or IDs
            new_content = re.sub(r'(<body.*?>)', r'\1' + reminder_html, content)
            
            with open(billing_index, 'w') as f:
                f.write(new_content)
            print(f"[{folder}] Status: REMIND (Due: {pay_due_date})")

        # CASE 3: ACTIVE STATE
        else:
            if os.path.exists(billing_index):
                os.remove(billing_index)
            else:
                print(f"[{folder}] Status: ACTIVE")

if __name__ == "__main__":
    update_billing()
