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("/")
    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:
        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, 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()
