import os
import configparser

# Replace $uid with the actual user ID
uid = os.getlogin()
config_file_path = f"C:\\Users\\{uid}\\AppData\\Roaming\\Nextcloud\\nextcloud.cfg"

# Ensure the configuration file exists
if not os.path.exists(config_file_path):
    raise FileNotFoundError(f"Configuration file not found at: {config_file_path}")

# Read and update the configuration
config = configparser.ConfigParser(strict=False)
config.optionxform = str  # Preserve case sensitivity for keys

# Read the file
config.read(config_file_path, encoding='utf-8')

# Ensure the [General] section exists
if 'General' not in config:
    config['General'] = {}

# Fix the main sync issues
config['General']['maxChunkSize'] = '50000000'

# Add sync monitoring improvements
config['General']['pollInterval'] = '5000'  # Check for changes every 5 seconds (default is 30000)
config['General']['forceSyncInterval'] = '3600'  # Force full sync every hour
config['General']['enableEtag'] = 'true'
config['General']['useNewBigFolderSizeLimit'] = 'true'
config['General']['newBigFolderSizeLimit'] = '500'  # MB threshold for asking about large folders

# Network timeout improvements
config['General']['timeout'] = '300'  # 5 minute timeout
config['General']['chunkTimeout'] = '120'  # 2 minute chunk timeout

# Update account-specific settings for better sync
account_section = '0'  # Your account is account 0
if f'{account_section}\\pollInterval' not in config['Accounts']:
    config['Accounts'][f'{account_section}\\pollInterval'] = '5000'

# Fix folder-specific sync issues
folder_key = f'{account_section}\\FoldersWithPlaceholders\\1'

# Ensure the folder isn't paused
if f'{folder_key}\\paused' in config['Accounts']:
    config['Accounts'][f'{folder_key}\\paused'] = 'false'

# Add folder-specific sync settings
config['Accounts'][f'{folder_key}\\pollInterval'] = '5000'
config['Accounts'][f'{folder_key}\\syncHiddenFiles'] = 'true'

# Enable more detailed logging (temporary for debugging)
if 'Logging' not in config:
    config['Logging'] = {}
config['Logging']['logLevel'] = '2'  # 0=Info, 1=Warning, 2=Critical
config['Logging']['logExpire'] = '24'  # Keep logs for 24 hours
config['Logging']['logFlush'] = 'true'

# Write the updated configuration back to the file
with open(config_file_path, 'w', encoding='utf-8') as configfile:
    config.write(configfile, space_around_delimiters=False)

print(f"Updated Nextcloud configuration in {config_file_path}")
print("\nChanges made:")
print("âœ“ Reduced poll interval to 5 seconds (was 30 seconds)")
print("âœ“ Added force sync every hour")
print("âœ“ Enabled ETag support for better change detection")
print("âœ“ Added network timeout improvements")
print("âœ“ Enabled detailed logging for debugging")
print("âœ“ Ensured folder sync is not paused")
