# -*- coding: utf-8 -*-
"""Pruebas del motor Atom SSL Manager (sin emitir certificados reales)."""
from __future__ import print_function
import os
import sys
import tempfile

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_ssl_engine as eng  # noqa: E402

HTTP = """
<VirtualHost *:80>
    ServerName colegio.atomschool.edu.pe
    ServerAlias www.colegio.atomschool.edu.pe intranet.local
    DocumentRoot /var/www/colegio
</VirtualHost>
"""

HTTPS = """
<VirtualHost *:443>
    ServerName api.atomschool.edu.pe
    DocumentRoot /var/www/api
    SSLEngine on
    SSLCertificateFile /tmp/does-not-exist.crt
</VirtualHost>
"""

LOCAL = """
<VirtualHost *:80>
    ServerName atomos.local
    DocumentRoot /var/www/atomos
</VirtualHost>
"""


def test_local_vs_public():
    assert eng.is_local_name("localhost")
    assert eng.is_local_name("atomos.local")
    assert eng.is_local_name("127.0.0.1")
    assert not eng.is_public_hostname("intranet.lan")
    assert eng.is_public_hostname("colegio.atomschool.edu.pe")
    assert eng.is_public_hostname("*.atomschool.edu.pe")


def test_parse_and_classify():
    blocks = eng.parse_vhost_blocks(HTTP + LOCAL, "test.conf")
    names = [b["server_name"] for b in blocks]
    assert "colegio.atomschool.edu.pe" in names
    assert "atomos.local" in names
    pub = [b for b in blocks if b["server_name"].startswith("colegio")][0]
    loc = [b for b in blocks if b["server_name"].endswith(".local")][0]
    pub["http_ports"], pub["https_ports"] = [80], []
    loc["http_ports"], loc["https_ports"] = [80], []
    eng.classify(pub)
    eng.classify(loc)
    assert pub["color"] == "rojo"
    assert loc["color"] == "gris"
    https = eng.parse_vhost_blocks(HTTPS, "ssl.conf")[0]
    assert https["ssl_engine"] is True
    assert https["cert_file"].endswith(".crt")


def test_scan_tree_and_eligible():
    td = tempfile.mkdtemp(prefix="atomos-ssl-")
    open(os.path.join(td, "a.conf"), "w", encoding="utf-8").write(HTTP + LOCAL)
    open(os.path.join(td, "b.conf"), "w", encoding="utf-8").write(HTTPS)
    rows = eng.scan_apache_tree(td)
    assert len(rows) == 3
    elig = eng.eligible_domains(rows)
    names = [e["name"] for e in elig]
    assert "colegio.atomschool.edu.pe" in names
    assert "atomos.local" not in names
    s = eng.summarize(rows)
    assert s["gris"] >= 1
    assert s["rojo"] >= 1


def test_desktop_and_timer_shipped():
    desk = os.path.join(ROOT, "overlay_tree", "usr", "share", "applications", "atomos-ssl-manager.desktop")
    assert os.path.isfile(desk)
    t = open(desk, encoding="utf-8").read()
    assert "Atom SSL Manager" in t
    assert "atomos-ssl-manager.py" in t
    timer = os.path.join(ROOT, "overlay_tree", "etc", "systemd", "system", "atomos-ssl-renew.timer")
    assert os.path.isfile(timer)
    ops = open(os.path.join(SCRIPTS, "atomos-ssl-ops.sh"), encoding="utf-8").read()
    assert "python3-certbot-apache" in ops
    assert "dnf install" in ops
    stack = open(os.path.join(SCRIPTS, "atomos-stack-install.sh"), encoding="utf-8").read()
    assert "atomos-ssl-ops.sh" in stack
    setup = open(os.path.join(SCRIPTS, "atomos-setup.py"), encoding="utf-8").read()
    assert "show_ssl_stage" in setup
    menu = open(os.path.join(SCRIPTS, "atomos-desktop.py"), encoding="utf-8").read()
    assert "Atom SSL Manager" in menu


def test_no_le_for_local():
    rows = [{"server_name": "localhost", "server_alias": [], "ssl_engine": False, "cert_file": "", "expires": None}]
    eng.classify(rows[0])
    assert eng.eligible_domains(rows) == []


if __name__ == "__main__":
    test_local_vs_public()
    test_parse_and_classify()
    test_scan_tree_and_eligible()
    test_desktop_and_timer_shipped()
    test_no_le_for_local()
    print("OK ssl tests")
