import os
import win32security
import ntsecuritycon as con
import sqlite3

dir_path = r"c:\MAMP\htdocs\withings"
db_path = r"c:\MAMP\htdocs\withings\withings.sqlite"

# 1. Delete to release any locks
if os.path.exists(db_path):
    os.remove(db_path)

# 2. Create the proper schema
conn = sqlite3.connect(db_path)
conn.execute("""
    CREATE TABLE IF NOT EXISTS patients (
        userid TEXT PRIMARY KEY,
        nom TEXT,
        prenom TEXT,
        access_token TEXT,
        refresh_token TEXT,
        scope TEXT,
        expires_in INTEGER,
        token_type TEXT,
        last_update TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )
""")
conn.commit()
conn.close()

# 3. Apply Everyone Full Control to file
def add_everyone_full_control(path):
    try:
        sd = win32security.GetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION)
        dacl = sd.GetSecurityDescriptorDacl()
        if dacl is None:
            dacl = win32security.ACL()
        # Everyone SID is S-1-1-0
        everyone, domain, type = win32security.LookupAccountName("", "Everyone")
        # For French it might be 'Tout le monde', win32security handles SIDs better?
        # Actually let's use the WellKnownSid for Everyone
        sid_everyone = win32security.CreateWellKnownSid(win32security.WinWorldSid)
        
        dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, sid_everyone)
        sd.SetSecurityDescriptorDacl(1, dacl, 0)
        win32security.SetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION, sd)
        print(f"Granted Everyone Full Control to {path}")
    except Exception as e:
        print(f"Failed to set ACL on {path}: {e}")

add_everyone_full_control(dir_path)
add_everyone_full_control(db_path)

print("DB Fixed!")
