from __future__ import annotations

import base64
import io
import zipfile

# Embedded LSA4 tunnel-enabled Task Scheduler local storage agent package.
# Uses Windows Task Scheduler instead of pywin32 Windows Service.
# This is used by the ERP Branch Storage Dashboard to generate branch-specific
# pre-configured agent ZIP files with .env already filled.
LSA4_ZIP_B64 = """
[encoded data, 55781 characters]
anV4CwABBAAAAAAEAAAAAFBLBQYAAAAAJQAlALsOAABnkwAAAAA=
"""


def build_agent_env(*, erp_base_url: str, node_code: str, node_secret: str, storage_root: str, tenant_id: int | str | None = None, branch_id: int | str | None = None, sync_interval_seconds: int = 30, request_timeout_seconds: int = 60, tunnel_enabled: bool = True, tunnel_reconnect_seconds: int = 10) -> str:
    erp_base_url = (erp_base_url or "").strip().rstrip("/")
    # Coolify/Traefik may forward the application request internally as HTTP even
    # when the public ERP URL is HTTPS. Public agent packages must use HTTPS so
    # tunnel.py derives a valid wss:// endpoint. Preserve explicit local test URLs.
    if erp_base_url.startswith("http://"):
        host = erp_base_url[7:].split("/", 1)[0].split(":", 1)[0].lower()
        if host not in {"localhost", "127.0.0.1", "::1"}:
            erp_base_url = "https://" + erp_base_url[7:]
    storage_root = (storage_root or r"D:\AuditFirmStorage").strip()
    return (
        f"ERP_BASE_URL={erp_base_url}\n"
        f"NODE_CODE={(node_code or '').strip()}\n"
        f"NODE_SECRET={(node_secret or '').strip()}\n"
        f"STORAGE_ROOT={storage_root}\n"
        f"TENANT_ID={'' if tenant_id is None else tenant_id}\n"
        f"AUDIT_FIRM_ID={'' if tenant_id is None else tenant_id}\n"
        f"BRANCH_ID={'' if branch_id is None else branch_id}\n"
        f"SYNC_INTERVAL_SECONDS={int(sync_interval_seconds or 30)}\n"
        f"POLL_INTERVAL_SECONDS={int(sync_interval_seconds or 30)}\n"
        f"REQUEST_TIMEOUT_SECONDS={int(request_timeout_seconds or 60)}\n"
        f"TUNNEL_ENABLED={str(bool(tunnel_enabled)).lower()}\n"
        f"TUNNEL_RECONNECT_SECONDS={int(tunnel_reconnect_seconds or 10)}\n"
    )


def build_preconfigured_agent_zip(*, env_text: str, include_admin_readme: bool = False) -> bytes:
    """Build branch-specific LSA4 tunnel-enabled ZIP.

    Partner/Branch Admin packages intentionally hide roadmap/readme text files and
    .env.example. The package still contains requirements.txt because pip needs it.
    """
    base = base64.b64decode(LSA4_ZIP_B64)
    src = zipfile.ZipFile(io.BytesIO(base), "r")
    buffer = io.BytesIO()
    with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_DEFLATED) as dst:
        replacements = {
            "run_agent.bat": (
                "@echo off\r\n"
                "setlocal\r\n"
                "cd /d \"%~dp0\"\r\n"
                "if not exist \".env\" (\r\n"
                "    echo ERROR: .env file is missing. Generate/download the configured agent package from ERP.\r\n"
                "    exit /b 1\r\n"
                ")\r\n"
                "if not exist \".venv\\Scripts\\python.exe\" (\r\n"
                "    echo ERROR: Python virtual environment is missing. Run install_task_scheduler.bat first.\r\n"
                "    exit /b 1\r\n"
                ")\r\n"
                "\".venv\\Scripts\\python.exe\" -m audit_storage_agent.main\r\n"
            ).encode("utf-8"),
            "install_task_scheduler.bat": (
                "@echo off\r\n"
                "setlocal\r\n"
                "cd /d \"%~dp0\"\r\n"
                "if not exist \".env\" (\r\n"
                "    echo ERROR: .env file is missing. Generate/download the configured agent package from ERP.\r\n"
                "    pause\r\n"
                "    exit /b 1\r\n"
                ")\r\n"
                "if not exist \".venv\\Scripts\\python.exe\" (\r\n"
                "    echo Creating virtual environment...\r\n"
                "    py -3 -m venv .venv\r\n"
                "    if errorlevel 1 (\r\n"
                "        echo ERROR: Unable to create the Python virtual environment.\r\n"
                "        pause\r\n"
                "        exit /b 1\r\n"
                "    )\r\n"
                ")\r\n"
                "\".venv\\Scripts\\python.exe\" -m pip install --upgrade pip\r\n"
                "if errorlevel 1 goto :install_failed\r\n"
                "\".venv\\Scripts\\python.exe\" -m pip install -r requirements.txt\r\n"
                "if errorlevel 1 goto :install_failed\r\n"
                "set \"AGENT_DIR=%~dp0\"\r\n"
                "set \"AGENT_PYTHON=%~dp0.venv\\Scripts\\python.exe\"\r\n"
                "powershell.exe -NoProfile -ExecutionPolicy Bypass -Command \"$ErrorActionPreference='Stop'; $taskName='AuditFirmStorageAgent'; $agentDir=$env:AGENT_DIR.TrimEnd('\\'); $python=$env:AGENT_PYTHON; $action=New-ScheduledTaskAction -Execute $python -Argument '-m audit_storage_agent.main' -WorkingDirectory $agentDir; $trigger=New-ScheduledTaskTrigger -AtStartup; $principal=New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest; $settings=New-ScheduledTaskSettingsSet -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1) -ExecutionTimeLimit ([TimeSpan]::Zero) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries; Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force | Out-Null; Start-ScheduledTask -TaskName $taskName\"\r\n"
                "if errorlevel 1 (\r\n"
                "    echo ERROR: Task Scheduler installation failed. Run this file as Administrator.\r\n"
                "    pause\r\n"
                "    exit /b 1\r\n"
                ")\r\n"
                "echo Audit Firm Storage Agent scheduled task installed and started successfully.\r\n"
                "echo The agent now runs in the background; no command window needs to remain open.\r\n"
                "pause\r\n"
                "exit /b 0\r\n"
                ":install_failed\r\n"
                "echo ERROR: Python dependency installation failed.\r\n"
                "pause\r\n"
                "exit /b 1\r\n"
            ).encode("utf-8"),
        }
        for info in src.infolist():
            name = info.filename.replace("\\", "/")
            lower = name.lower()
            if name == ".env" or lower.endswith(".env.example"):
                continue
            if (not include_admin_readme) and lower.endswith(".txt") and lower != "requirements.txt":
                continue
            dst.writestr(info, replacements.get(name, src.read(info.filename)))
        dst.writestr(".env", env_text)
        if include_admin_readme:
            dst.writestr(
                "README_AUTO_SETUP.txt",
                "This LSA4 tunnel-enabled Task Scheduler agent package was generated from Audit ERP Branch Storage Auto Setup.\n"
                "The .env file is pre-filled for this branch storage node.\n\n"
                "Recommended setup on branch storage computer:\n"
                "1. Extract this ZIP to C:\\AuditFirmStorageAgent or any fixed folder.\n"
                "2. Right-click Command Prompt / PowerShell and Run as Administrator.\n"
                "3. Run check_config.bat.\n"
                "4. Run install_task_scheduler.bat.\n"
                "5. Check Documents -> Branch Storage Dashboard in ERP for Online/Tunnel status.\n"
            )
    return buffer.getvalue()
