"""Update the Windows Task Scheduler task to enable StartWhenAvailable (catch-up missed runs)."""
import subprocess
import tempfile
import os

tmpdir = tempfile.gettempdir()
updated_path = os.path.join(tmpdir, "biznode_task_updated.xml")

# Export current task XML as raw bytes
result = subprocess.run(
    ["schtasks", "/Query", "/TN", "BizNodeDailyBackup", "/XML"],
    capture_output=True,
)
raw = result.stdout

# It comes out as ASCII/UTF-8 with \r\r\n (Git Bash artifact)
xml = raw.decode("utf-8", errors="replace")

# Fix line endings: \r\r\n -> \n, then back to \r\n
xml = xml.replace('\r\r\n', '\n').replace('\r\n', '\n').replace('\r', '\n')

# Remove encoding declaration — let parser auto-detect
xml = xml.replace(' encoding="UTF-16"', '')

# Enable StartWhenAvailable (catch-up missed runs)
xml = xml.replace(
    "<DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>",
    "<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>",
)
xml = xml.replace(
    "<StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>",
    "<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>\n    <StartWhenAvailable>true</StartWhenAvailable>",
)
# Add working directory
xml = xml.replace(
    "<Arguments>",
    "<WorkingDirectory>C:\\nodesrunning\\biznodemainnode</WorkingDirectory>\n      <Arguments>",
    1,
)

# Write as UTF-8 with proper Windows line endings
xml = xml.replace('\n', '\r\n')
with open(updated_path, "w", encoding="utf-8", newline="") as f:
    f.write(xml)

# Re-import
result = subprocess.run(
    ["schtasks", "/Create", "/TN", "BizNodeDailyBackup", "/XML", updated_path, "/F"],
    capture_output=True, text=True,
)
if result.returncode == 0:
    print("Task updated successfully!")
    print("  - StartWhenAvailable: enabled (catch-up missed runs)")
    print("  - Battery: allowed to run on battery")
    print("  - Working directory set")
else:
    print(f"Failed: {result.stderr}")
