# -*- coding: utf-8 -*-
"""Pruebas de escritorio sin arrancar la ISO (host Windows/Linux)."""
from __future__ import print_function
import json
import os
import shutil
import sys
import tempfile
import zipfile

ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
SCRIPTS = os.path.join(ROOT, "overlay_tree", "usr", "share", "atomos", "scripts")
sys.path.insert(0, SCRIPTS)

import atomos_extract  # noqa: E402
import atomos_altcodes  # noqa: E402


def test_archive_ext():
    assert atomos_extract.is_archive("a.zip")
    assert atomos_extract.is_archive("b.rar")
    assert atomos_extract.is_archive("c.7z")
    assert not atomos_extract.is_archive("game.exe")


def test_extract_zip_sibling():
    td = tempfile.mkdtemp(prefix="atomos-ex-")
    try:
        zpath = os.path.join(td, "paquete.zip")
        with zipfile.ZipFile(zpath, "w") as z:
            z.writestr("hola.txt", "atomos")
        dest = atomos_extract.extract(zpath)
        assert os.path.isdir(dest)
        assert dest.startswith(td)
        assert os.path.isfile(os.path.join(dest, "hola.txt"))
        assert os.path.basename(os.path.dirname(dest)) != "Downloads"
    finally:
        shutil.rmtree(td, ignore_errors=True)


def test_pins():
    path = os.path.join(ROOT, "overlay_tree", "usr", "share", "atomos", "taskbar-pins.json")
    pins = json.load(open(path, encoding="utf-8"))
    assert len(pins) >= 10
    names = [p["name"] for p in pins]
    assert names[0] == "Inicio"
    assert names[9] == "Writer"
    assert "atom-webapp" in pins[5]["cmd"]
    assert "/zion" in pins[5]["cmd"]


def test_hotkeys_in_openbox():
    xml = os.path.join(ROOT, "overlay_tree", "etc", "xdg", "xdg-Lubuntu", "openbox", "lxqt-rc.xml")
    txt = open(xml, encoding="utf-8").read()
    for n in range(10):
        assert 'key="A-%d"' % n not in txt
        assert 'key="W-%d"' % n in txt
    assert 'key="W-l"' in txt
    assert 'key="W-e"' in txt
    assert "<drawContents>no</drawContents>" in txt
    assert "<animateIconify>no</animateIconify>" in txt
    assert "atomos-outline-drag.py" in txt
    assert "<action name=\"Move\"/>" not in txt


def test_wine_refuses_anticheat():
    sh = open(os.path.join(SCRIPTS, "atomos-wine.sh"), encoding="utf-8").read()
    assert "valorant" in sh.lower()
    assert "vanguard" in sh.lower()
    assert "ricochet" in sh.lower()
    assert "wine32" in sh
    assert "msiexec" in sh
    assert "wineserver" in sh
    assert "mscoree" in sh
    assert "/mnt/c/Users/AtomOS/.wine" in sh
    # CPU-Z es PE32: el wrapper wine (32+64), nunca wine64 primero.
    assert "command -v wine" in sh
    assert "*cod.exe*" not in sh
    wine_desk = open(os.path.join(ROOT, "overlay_tree", "usr", "share", "applications", "wine.desktop"), encoding="utf-8").read()
    assert "atomos-wine.sh" in wine_desk
    assert "Exec=wine start" not in wine_desk
    expl = open(os.path.join(SCRIPTS, "atomos_explorer.py"), encoding="utf-8").read()
    desk = open(os.path.join(SCRIPTS, "atomos-desktop.py"), encoding="utf-8").read()
    assert "def run_wine" in expl
    assert "def run_wine" in desk
    live = open(os.path.join(SCRIPTS, "atomos-live-init.sh"), encoding="utf-8").read()
    assert "atomos-wine.sh --init" in live


def test_alt_ascii():
    assert len(atomos_altcodes.CP437) == 256
    assert atomos_altcodes.char_for(64, False) == "@"
    assert atomos_altcodes.char_for(1, False) == "☺"
    assert atomos_altcodes.char_for(3, False) == "♥"
    assert atomos_altcodes.char_for(164, True) == chr(164)


def test_pwa_urls_and_icons():
    apps = json.load(open(os.path.join(ROOT, "overlay_tree", "usr", "share", "atomos", "pwa", "apps.json"), encoding="utf-8"))
    need = {
        "atom-zion": "/zion",
        "atom-matrix": "/matrix",
        "atom-flash": "atomflash",
        "atom-chat": "/chat",
        "atom-cms": "atomcms",
        "atom-studio": "atomstudio",
    }
    by_id = {a["id"]: a for a in apps}
    for aid, frag in need.items():
        assert aid in by_id, aid
        assert frag in by_id[aid]["url"], (aid, by_id[aid]["url"])
        icon = os.path.join(ROOT, "overlay_tree") + by_id[aid]["icon"].replace("/", os.sep)
        # path is /usr/share/...
        icon = os.path.join(ROOT, "overlay_tree", by_id[aid]["icon"].lstrip("/").replace("/", os.sep))
        assert os.path.isfile(icon) and os.path.getsize(icon) > 100, icon


def test_desktop_exec_webapp():
    z = os.path.join(ROOT, "overlay_tree", "usr", "share", "applications", "atom-zion.desktop")
    t = open(z, encoding="utf-8").read()
    assert "atom-webapp" in t
    assert "https://atomschool.edu.pe/zion" in t
    assert "Icon=/usr/share/atomos/pwa/atom-zion.png" in t
    nav = open(os.path.join(SCRIPTS, "atom-navegador.sh"), encoding="utf-8").read()
    assert "--atom-url=" in nav
    web = open(os.path.join(ROOT, "overlay_tree", "usr", "bin", "atom-webapp"), encoding="utf-8").read()
    assert "--atom-url=" in web
    grub = open(os.path.join(ROOT, "iso_inject", "boot", "grub", "grub.cfg"), encoding="utf-8").read()
    assert "Instalar Atom OS" in grub
    assert "atomos-install=1" in grub
    assert "timeout_style=menu" in grub
    setup = open(os.path.join(SCRIPTS, "atomos-setup.py"), encoding="utf-8").read()
    assert "def show_disk" in setup
    assert "Instalar en esta partición" in setup
    assert "20613902911" in setup
    assert "botoninicio.png" in setup
    assert "asistente discos PRIMERO" in open(os.path.join(SCRIPTS, "atomos-live-init.sh"), encoding="utf-8").read()
    grub = open(os.path.join(ROOT, "iso_inject", "boot", "grub", "grub.cfg"), encoding="utf-8").read()
    assert grub.find("Instalar Atom OS") < grub.find("Probar Atom OS")


def test_lamp_debs_present():
    d = os.path.join(ROOT, "overlay_tree", "usr", "share", "atomos", "debs")
    names = os.listdir(d)
    assert any(n.startswith("apache2_") for n in names)
    assert any(n.startswith("mariadb-server_") for n in names)
    assert any("php8.1-mysql" in n for n in names)
    sh = open(os.path.join(SCRIPTS, "atomos-devstack.sh"), encoding="utf-8").read()
    assert "start_apache" in sh
    assert "start_mysql" in sh
    assert "sql_init" in sh
    assert sh.count("<<'SQL'") == 1
    assert "wine" not in sh.split("LAMP")[0] or "dpkg LAMP" in sh
    brand = open(os.path.join(SCRIPTS, "atomos-www-brand.sh"), encoding="utf-8").read()
    assert "atom-school-logo.png" in brand
    assert "000-default" in brand
    html = open(os.path.join(ROOT, "overlay_tree", "usr", "share", "atomos", "www", "index.html"), encoding="utf-8").read()
    assert "Atom School" in html
    assert "ATOM OS" in html
    assert "Ubuntu" not in html
    assert "Debian" not in html
    panel = open(os.path.join(SCRIPTS, "atomos_server_panel.py"), encoding="utf-8").read()
    assert "icons/stack/apache.png" in panel
    assert "border-radius:9px" in panel
    assert "brand_ver" in panel
    cpio = open(os.path.join(ROOT, "build_cpio.ps1"), encoding="utf-8").read()
    assert "bgrt-fallback.png" in cpio
    assert "watermark.png" in cpio
    mk = open(os.path.join(SCRIPTS, "atomos-mkboot.sh"), encoding="utf-8").read()
    assert "bgrt-fallback.png" in mk
    osrel = open(os.path.join(ROOT, "overlay_tree", "etc", "os-release"), encoding="utf-8").read()
    assert 'PRETTY_NAME="Atom OS"' in osrel
    ply = open(os.path.join(ROOT, "overlay_tree", "usr", "share", "plymouth", "themes", "lubuntu-text", "lubuntu-text.plymouth"), encoding="utf-8").read()
    assert "title=Atom OS" in ply
    assert "Lubuntu" not in ply
    desk = open(os.path.join(SCRIPTS, "atomos-desktop.py"), encoding="utf-8").read()
    assert "Qt.Popup" in desk
    assert "Crear carpeta" in desk
    assert "Comprimir" in desk
    settings = open(os.path.join(SCRIPTS, "atomos_settings.py"), encoding="utf-8").read()
    assert "Atom OS Update" in settings
    assert "Windows Update" not in settings
    ext = open(os.path.join(SCRIPTS, "atomos_extract.py"), encoding="utf-8").read()
    assert "def compress" in ext
    eng = open(os.path.join(SCRIPTS, "atomos_install_engine.py"), encoding="utf-8").read()
    assert "rarlab" in eng
    assert os.path.isfile(os.path.join(SCRIPTS, "atomos-installer.py"))
    assert os.path.isfile(os.path.join(SCRIPTS, "atomos-update.py"))
    assert os.path.isfile(os.path.join(SCRIPTS, "atomos-apps.py"))
    mime = open(os.path.join(ROOT, "overlay_tree", "etc", "xdg", "mimeapps.list"), encoding="utf-8").read()
    assert "atomos-installer.desktop" in mime
    cpio = open(os.path.join(ROOT, "build_cpio.ps1"), encoding="utf-8").read()
    assert "lubuntu-text.plymouth" in cpio
    assert "title=Atom OS" in cpio or "Atom OS" in cpio
    assert "drag.exec_" not in desk
    assert "Nombre de la carpeta" in desk
    assert "_item_key" in desk
    expl = open(os.path.join(SCRIPTS, "atomos_explorer.py"), encoding="utf-8").read()
    assert 'kind": "network"' in expl or 'kind": "network"' in expl.replace("'", '"')
    assert "atomos_net" in expl
    assert "Nombre de la carpeta" in expl
    desk_entry = open(os.path.join(ROOT, "overlay_tree", "usr", "share", "applications", "atomos-explorer.desktop"), encoding="utf-8").read()
    assert "%U" in desk_entry
    chrome = open(os.path.join(SCRIPTS, "atomos_chrome.py"), encoding="utf-8").read()
    assert "center_on_screen" in chrome
    assert "class OutlineGhost" in chrome
    assert "DRAG_THRESHOLD" in chrome
    assert os.path.isfile(os.path.join(SCRIPTS, "atomos-outline-drag.py"))
    live = open(os.path.join(SCRIPTS, "atomos-live-init.sh"), encoding="utf-8").read()
    assert "pkill -x picom" in live
    assert "picom --backend" not in live
    inst = open(os.path.join(SCRIPTS, "atomos-installer.py"), encoding="utf-8").read()
    assert "mkdtemp" in inst
    assert "dest=work" in inst
    assert "dest=None" in ext
    ff = open(os.path.join(ROOT, "overlay_tree", "etc", "firefox", "policies", "policies.json"), encoding="utf-8").read()
    assert "DefaultDownloadDirectory" in ff
    assert os.path.isfile(os.path.join(SCRIPTS, "atomos_net.py"))
    assert os.path.isfile(os.path.join(SCRIPTS, "atomos_xdg.py"))
    assert os.path.isfile(os.path.join(SCRIPTS, "atomos-net-helper.sh"))
    pol = open(os.path.join(ROOT, "overlay_tree", "usr", "share", "polkit-1", "actions", "pe.atomschool.install.policy"), encoding="utf-8").read()
    assert "pe.atomschool.network" in pol
    live = open(os.path.join(SCRIPTS, "atomos-live-init.sh"), encoding="utf-8").read()
    assert "atomos_xdg.py" in live
    assert "band_origin" in desk
    assert "file_pixmap" in desk
    assert "_archive_stem" in ext
    assert "_member_rel" in ext
    setup = open(os.path.join(SCRIPTS, "atomos-setup.py"), encoding="utf-8").read()
    assert "def do_reboot" in setup
    assert "atomos-reboot-helper.sh" in setup
    assert "systemctl" in open(os.path.join(SCRIPTS, "atomos-reboot-helper.sh"), encoding="utf-8").read()
    xcu = open(
        os.path.join(ROOT, "overlay_tree", "home", "atomos", ".config", "libreoffice", "4", "user", "registrymodifications.xcu"),
        encoding="utf-8",
    ).read()
    assert "UseSystemFileDialog" in xcu
    assert "FilePickerPlacesUrls" in xcu
    assert "FilePickerPlacesNames" in xcu
    assert "file:///mnt/c" in xcu
    assert "file:///mnt/d" in xcu
    assert "Disco local (C:)" in xcu
    assert "Escritorio" in xcu
    assert "Descargas" in xcu
    xdg = open(os.path.join(SCRIPTS, "atomos_xdg.py"), encoding="utf-8").read()
    assert "def iter_places" in xdg
    assert "def _write_lo_places" in xdg
    assert "FilePickerPlacesUrls" in xdg
    assert "/mnt/c" in xdg
    bm = open(
        os.path.join(ROOT, "overlay_tree", "etc", "skel", ".config", "gtk-3.0", "bookmarks"),
        encoding="utf-8",
    ).read()
    assert "Disco local (C:)" in bm
    assert "Escritorio" in bm
    lo = open(os.path.join(SCRIPTS, "atomos-lo.sh"), encoding="utf-8").read()
    assert "/usr/bin/libreoffice" in lo
    assert "atomos_lo_hook.py" in lo
    fd = open(os.path.join(SCRIPTS, "atomos_filedialog.py"), encoding="utf-8").read()
    assert "Disco local (C:)" in fd
    assert "Música" in fd
    assert "Escritorio" in fd
    assert "def pick_file" in fd
    assert "Guardar como" in fd
    hook = open(os.path.join(SCRIPTS, "atomos_lo_hook.py"), encoding="utf-8").read()
    assert "atomos_filedialog.py" in hook
    assert ".uno:SaveAs" in hook
    calc_d = open(os.path.join(ROOT, "overlay_tree", "usr", "share", "applications", "libreoffice-calc.desktop"), encoding="utf-8").read()
    assert "atomos-lo.sh" in calc_d
    codex = open(os.path.join(SCRIPTS, "atomos-codex-install.sh"), encoding="utf-8").read()
    assert "https://chatgpt.com/codex/install.sh" in codex
    assert "CODEX_NON_INTERACTIVE" in codex
    assert "ATOMOS_PROG" in codex
    setup = open(os.path.join(SCRIPTS, "atomos-setup.py"), encoding="utf-8").read()
    assert "Codex (ChatGPT)" in setup
    stack = open(os.path.join(SCRIPTS, "atomos-stack-install.sh"), encoding="utf-8").read()
    assert "atomos-codex-install.sh" in stack
    assert os.path.isfile(os.path.join(ROOT, "overlay_tree", "usr", "share", "applications", "atomos-codex.desktop"))
    desk = open(os.path.join(SCRIPTS, "atomos-desktop.py"), encoding="utf-8").read()
    assert "wmctrl" in desk
    assert "_restore" in desk
    assert "_click_pin" in desk
    disks = open(os.path.join(SCRIPTS, "atomos-win-disks.sh"), encoding="utf-8").read()
    assert "disco con datos, no formatear" in disks
    xdg = open(os.path.join(SCRIPTS, "atomos_xdg.py"), encoding="utf-8").read()
    assert "def persist_root" in xdg
    assert "/mnt/c/Users/AtomOS" in xdg
    assert os.path.isfile(os.path.join(SCRIPTS, "atomos_portal.py"))
    portal = open(os.path.join(SCRIPTS, "atomos_portal.py"), encoding="utf-8").read()
    assert "atomos_filedialog.py" in portal
    assert "org.freedesktop.portal.FileChooser" in portal


def test_compress_folder_extract_elsewhere():
    src = tempfile.mkdtemp(prefix="atomos-src-")
    other = tempfile.mkdtemp(prefix="atomos-dst-")
    try:
        folder = os.path.join(src, "Tareas")
        os.makedirs(folder)
        open(os.path.join(folder, "nota.txt"), "w", encoding="utf-8").write("hola")
        zpath = atomos_extract.compress([folder], "zip")
        assert os.path.basename(zpath) == "Tareas.zip"
        copied = os.path.join(other, "Tareas.zip")
        shutil.copy2(zpath, copied)
        dest = atomos_extract.extract(copied)
        assert dest.startswith(other), dest
        assert os.path.isfile(os.path.join(dest, "nota.txt")), os.listdir(dest)
        assert not dest.startswith(src)
        doc = os.path.join(src, "informe.odt")
        open(doc, "w").write("x")
        z2 = atomos_extract.compress([doc], "zip")
        assert os.path.basename(z2) == "informe.zip"
    finally:
        shutil.rmtree(src, ignore_errors=True)
        shutil.rmtree(other, ignore_errors=True)


def test_extract_to_temp_leaves_archive():
    td = tempfile.mkdtemp(prefix="atomos-ins-")
    work = tempfile.mkdtemp(prefix="atomos-work-")
    try:
        zpath = os.path.join(td, "rarlinux-x64.zip")
        with zipfile.ZipFile(zpath, "w") as z:
            z.writestr("rar", "x")
            z.writestr("unrar", "y")
        dest = atomos_extract.extract(zpath, dest=work)
        assert os.path.isfile(zpath)
        assert dest.startswith(work)
        assert not os.path.isdir(os.path.join(td, "rarlinux-x64"))
        assert os.path.isfile(os.path.join(work, "rar"))
    finally:
        shutil.rmtree(td, ignore_errors=True)
        shutil.rmtree(work, ignore_errors=True)


if __name__ == "__main__":
    test_archive_ext()
    test_extract_zip_sibling()
    test_pins()
    test_hotkeys_in_openbox()
    test_wine_refuses_anticheat()
    test_alt_ascii()
    test_pwa_urls_and_icons()
    test_desktop_exec_webapp()
    test_lamp_debs_present()
    test_extract_to_temp_leaves_archive()
    test_compress_folder_extract_elsewhere()
    print("OK audit tests")
