#!/usr/bin/env python3
"""
Gibt pipe-getrennt die Zugangsdaten aller aktiven Geräte + ihrer Switche aus.
Wird von poe.sh (Bash) konsumiert, um Erreichbarkeit zu prüfen und im
Fehlerfall den PoE-Port neu zu starten.
"""
import sqlite3
from app import decrypt_password, DB_PATH


def generate_ips_list():
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row

    switches = {
        row["hostname"]: row
        for row in conn.execute("""
            SELECT switches.hostname, switches.ip, switches.ssh_port,
                   credentials.username AS username, credentials.password AS password
            FROM switches
            LEFT JOIN credentials ON credentials.id = switches.credential_id
        """)
    }

    devices = conn.execute("""
        SELECT mac, ip, port, name, switch_hostname
        FROM devices
        WHERE is_active=1 AND deleted_at IS NULL
    """).fetchall()
    conn.close()

    for dev in devices:
        switch = switches.get(dev["switch_hostname"])
        if switch and switch["password"]:
            switch_ip = switch["ip"]
            switch_ssh_port = switch["ssh_port"] or 22
            switch_user = switch["username"]
            switch_pass = decrypt_password(switch["password"])
        else:
            switch_ip = switch["ip"] if switch else ""
            switch_ssh_port = (switch["ssh_port"] if switch else None) or 22
            switch_user = ""
            switch_pass = ""

        port = dev["port"] or ""
        print(
            f"{dev['ip']}|"
            f"{dev['name']}|"
            f"{switch_ip}|"
            f"{switch_ssh_port}|"
            f"{dev['switch_hostname'] or 'kein Switch'}|"
            f"{port}|"
            f"{switch_user}|"
            f"{switch_pass}|"
            f"{dev['mac']}"
        )


if __name__ == "__main__":
    generate_ips_list()
