import requests
import psutil
import socket
import time
import json

# ==========================================
# ⚙️ CONFIGURATION
# ==========================================
# 1. LOCALHOST URL (Use this when testing on XAMPP)
API_URL = "http://localhost/HardGuard/api/agent.php"

# 2. CLOUD URL (Uncomment the line below when testing on InfinityFree)
# API_URL = "https://hardguard.fwh.is/api/agent.php"

# The Database ID of your Admin account (If you are the only user, it is usually 1)
ADMIN_USER_ID = 1 
PC_NAME = socket.gethostname()

def get_connected_drives():
    """Scans the local computer for connected drives (Ignores C: for safety)"""
    drives = []
    # all=True helps catch USBs that Windows sometimes categorizes strangely
    partitions = psutil.disk_partitions(all=True) 
    
    for p in partitions:
        # EXTREME SAFETY: Never list the main C:\ drive
        if "C:" in p.device:
            continue
        
        # Skip empty drives (like CD-ROMs with no disk inserted)
        if p.fstype == '':
            continue
            
        try:
            usage = psutil.disk_usage(p.mountpoint)
            capacity_gb = int(usage.total / (1024 ** 3))
            
            drives.append({
                "letter": p.device.replace('\\', ''),
                "model": f"External/Local Disk ({p.fstype})",
                "capacity": capacity_gb
            })
        except PermissionError:
            continue # Skip drives we don't have Windows permission to read
            
    return drives

def sync_drives_with_cloud():
    """Sends the list of plugged-in drives to the PHP website"""
    drives = get_connected_drives()
    
    # DEBUG: Print what the daemon actually sees!
    print(f"\r[🔍] Scanned PC. Found {len(drives)} wipeable drive(s)...", end="")
    
    data = {
        'action': 'sync_drives',
        'user_id': ADMIN_USER_ID,
        'pc_name': PC_NAME,
        'drives': json.dumps(drives)
    }
    try:
        res = requests.post(API_URL, data=data)
        if res.status_code != 200:
            print(f"\n[!] Server returned Error {res.status_code}: {res.text}")
    except requests.exceptions.RequestException as e:
        print(f"\n[!] Network Error: Could not reach {API_URL}")

def check_for_wipe_jobs():
    """Asks the website if the Admin clicked the 'Wipe' button"""
    try:
        res = requests.post(API_URL, data={'action': 'get_jobs', 'user_id': ADMIN_USER_ID})
        
        # Only process if the server actually returned JSON
        if res.status_code == 200 and res.text.strip():
            data = res.json()
            if data.get('job'):
                job = data['job']
                print(f"\n\n[⚠️] WIPE COMMAND RECEIVED FROM DASHBOARD: Formatting Drive {job['drive_letter']}...")
                execute_wipe_simulation(job['id'], job['drive_letter'])
            
    except json.JSONDecodeError:
        pass # The server didn't return JSON (maybe a blank page), ignore it
    except Exception as e:
        pass # Ignore silent network errors while idling

def execute_wipe_simulation(job_id, drive_letter):
    """Simulates a wipe by slowly ticking progress up to 100%"""
    for i in range(1, 101, 10):
        print(f"[*] Sanitizing {drive_letter} ... {i}%")
        requests.post(API_URL, data={
            'action': 'update_progress',
            'job_id': job_id,
            'progress': i,
            'status': 'In Progress'
        })
        time.sleep(2) 
        
    print(f"[✓] Drive {drive_letter} successfully sanitized!\n")
    print("⏳ Resuming standby mode...")
    
    requests.post(API_URL, data={
        'action': 'update_progress',
        'job_id': job_id,
        'progress': 100,
        'status': 'Completed'
    })

# ==========================================
# 🚀 MAIN DAEMON LOOP
# ==========================================
if __name__ == "__main__":
    print("==================================================")
    print(f"🛡️ CipherGuard Hardware Agent started on {PC_NAME}")
    print(f"📡 Connecting to: {API_URL}")
    print("==================================================\n")
    print("⏳ Waiting for hardware changes or wipe commands...")
    
    while True:
        sync_drives_with_cloud() 
        check_for_wipe_jobs()    
        time.sleep(3) # Check every 3 seconds