import os
import time
import hashlib
import requests
import json
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

# --- Configuration ---
SERVER_URL = "http://your-wordpress-site.com/wp-content/themes/gllownite/api-sync.php"
SYNC_FOLDER = "./sync_me"
USERNAME = "your_username"
PASSWORD = "your_password"
# ---------------------

class SyncHandler(FileSystemEventHandler):
    def __init__(self, api_url, auth):
        self.api_url = api_url
        self.auth = auth
        self.tasks = []
        self.refresh_tasks()

    def refresh_tasks(self):
        """Fetch active sync tasks from the server."""
        try:
            response = requests.get(f"{self.api_url}?action=get_tasks", auth=self.auth)
            if response.status_code == 200:
                self.tasks = response.json().get('tasks', [])
                print(f"[*] Loaded {len(self.tasks)} sync tasks from server.")
            else:
                print(f"[!] Error refreshing tasks: Server responded with status {response.status_code}")
        except Exception as e:
            print(f"[!] Error refreshing tasks: {e}")

    def is_path_active(self, path):
        """Check if the given path is part of an active sync task."""
        path = os.path.abspath(path).replace('\\', '/')
        for task in self.tasks:
            # Ensure task['local_path'] is also absolute and normalized for comparison
            task_path = os.path.abspath(task['local_path']).replace('\\', '/')
            if path.startswith(task_path):
                return task['status'] == 'active'
        return False

    def on_modified(self, event):
        if not event.is_directory and self.is_path_active(event.src_path):
            self.sync_file(event.src_path)

    def on_created(self, event):
        if not event.is_directory and self.is_path_active(event.src_path):
            self.sync_file(event.src_path)

    def sync_file(self, file_path):
        rel_path = os.path.relpath(file_path, SYNC_FOLDER)
        print(f"[*] Syncing: {rel_path}")
        
        file_hash = self.get_file_hash(file_path)
        file_size = os.path.getsize(file_path)
        last_modified = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getmtime(file_path)))

        # 1. Upload Meta
        try:
            response = requests.post(self.api_url, auth=self.auth, data={
                'action': 'upload_meta',
                'file_path': rel_path,
                'file_hash': file_hash,
                'file_size': file_size,
                'last_modified': last_modified
            })
            result = response.json()
            
            if result.get('status') == 'required':
                # 2. Upload File
                file_id = result.get('file_id')
                print(f"[+] Uploading content for {rel_path} (ID: {file_id})...")
                with open(file_path, 'rb') as f:
                    requests.post(self.api_url, auth=self.auth, data={
                        'action': 'upload_chunk',
                        'file_id': file_id
                    }, files={'file': f})
                print(f"[OK] {rel_path} synced.")
            else:
                print(f"[-] {rel_path} is already up to date.")
        except Exception as e:
            print(f"[!] Error syncing {rel_path}: {e}")

    def get_file_hash(self, file_path):
        sha256_hash = hashlib.sha256()
        with open(file_path, "rb") as f:
            for byte_block in iter(lambda: f.read(4096), b""):
                sha256_hash.update(byte_block)
        return sha256_hash.hexdigest()

def main():
    if not os.path.exists(SYNC_FOLDER):
        os.makedirs(SYNC_FOLDER)

    # Simple login (you'd need to adapt this to your WP login flow)
    # For prototype purposes, assume we handle auth via session cookies after manual login or a dedicated token
    print(f"[*] Starting Sync Service on {SYNC_FOLDER}...")
    print(f"[*] Server: {SERVER_URL}")

    # Setup authentication
    auth = (USERNAME, PASSWORD)
    
    event_handler = SyncHandler(SERVER_URL, auth)
    observer = Observer()
    
    # In a real app, we'd watch multiple folders based on task list
    # For prototype, we watch the SYNC_FOLDER but only sync if it's active in the task list
    observer.schedule(event_handler, SYNC_FOLDER, recursive=True)
    
    print(f"[*] Monitoring {SYNC_FOLDER}...")
    observer.start()
    
    try:
        while True:
            time.sleep(60)
            event_handler.refresh_tasks() # Periodic refresh
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

if __name__ == "__main__":
    main()
