"""Genere un fichier Excel avec le tableau Tag V3 -> Rule Type + QQL/Regex + couleur.

Usage:
    python tools/gen_tags_v3_xlsx.py [chemin_sortie.xlsx]
"""
import sys
from pathlib import Path

try:
    from openpyxl import Workbook
    from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
    from openpyxl.utils import get_column_letter
except ImportError:
    print("[ERR] pip install openpyxl")
    sys.exit(1)


TAGS = [
    ("OS-LIN", "Operating System", "Linux", "4CAF50"),
    ("OS-WIN", "Operating System", "Windows", "2196F3"),
    ("OS-WIN-SRV", "Operating System", "Windows Server", "1976D2"),
    ("OS-ESX", "Operating System", "ESXi", "9C27B0"),
    ("ENV-PRD", "Asset Search", "name: vp* or name: sp* or name: lp* or name: ls-*", "F44336"),
    ("ENV-REC", "Asset Search", "name: vr* or name: sr* or name: lr*", "FF9800"),
    ("ENV-PPR", "Asset Search", "name: vi* or name: si* or name: vo*", "FFC107"),
    ("ENV-TST", "Asset Search", "name: vv* or name: vt*", "CDDC39"),
    ("ENV-DEV", "Asset Search", "name: vd* or name: sd*", "8BC34A"),
    ("EQT-VIR", "Asset Search", "name: v*", "00BCD4"),
    ("EQT-SRV", "Asset Search", "name: l* or name: s*", "03A9F4"),
    ("EQT-SWI", "Asset Search", "name: n*", "4DD0E1"),
    ("POS-FL", "Asset Search", 'name: "*bot*" or name: "*boo*" or name: "*boc*" or name: "*afl*" or name: "*sup*"', "009688"),
    ("POS-INF", "Asset Search", 'name: "*dsi*" or name: "*cyb*" or name: "*iad*" or name: "*bur*" or name: "*ecm*" or name: "*log*" or name: "*vid*" or name: "*ges*" or name: "*mon*"', "3F51B5"),
    ("POS-PEA", "Asset Search", 'name: "*pea*" or name: "*osa*" or name: "*svp*" or name: "*adv*" or name: "*rpa*" or name: "*rpn*" or name: "ls-*"', "673AB7"),
    ("POS-TRA", "Asset Search", 'name: "*ame*" or name: "*tra*" or name: "*dai*" or name: "*pat*" or name: "*rau*" or name: "*dep*" or name: "*exp*" or name: "*sig*" or name: "*air*"', "E91E63"),
    ("POS-BI", "Asset Search", 'name: "*dec*" or name: "*sas*" or name: "*bip*" or name: "*apt*" or name: "*pbi*" or name: "*rep*"', "FF5722"),
    ("POS-GES", "Asset Search", 'name: "*int*" or name: "*agt*" or name: "*pin*" or name: "*ech*"', "795548"),
    ("POS-DMZ", "Asset Search", 'name: "*ssi*"', "607D8B"),
    ("TAG-OBS", "Operating System", r"Windows Server 2008|Windows Server 2012|CentOS release 6|Red Hat Enterprise Linux Server release 6", "B71C1C"),
    ("TAG-EMV", "Asset Search", 'name: "*emv*" or name: "*pci*"', "D500F9"),
]

STATIC_MANUAL = [
    ("TAG-SED", "Securite Exposition Directe — IP publique / NAT direct", "C62828"),
    ("TAG-SEI", "Securite Exposition Indirecte — derriere frontal", "EF6C00"),
    ("TAG-DEC", "Decommissionnement en cours", "6D4C41"),
    ("TAG-INT", "Integration / Implementation en cours", "FDD835"),
    ("TAG-SIC", "Zone SIC — Systeme Information Classifie", "1A237E"),
    ("TAG-SIA", "Zone SIA — Systeme Information Administration", "283593"),
]

PREFIXES = [
    ("APP-xxx", "Application hebergee — APP-SAT, APP-JIRA, APP-GLPI..."),
    ("BDD-xxx", "Type de base de donnees — BDD-ORA, BDD-PG, BDD-SQL..."),
    ("VRF-xxx", "VRF reseau — VRF-TRAFIC, VRF-EMV..."),
    ("MID-xxx", "Middleware — MID-TOMCAT, MID-HAPROXY..."),
]


def main():
    out = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("SANEF_Qualys_Tags_V3_RuleTypes.xlsx")

    wb = Workbook()

    thin = Side(border_style="thin", color="CCCCCC")
    border = Border(left=thin, right=thin, top=thin, bottom=thin)
    header_font = Font(bold=True, color="FFFFFF", size=11)
    header_fill = PatternFill(start_color="1F4E79", end_color="1F4E79", fill_type="solid")
    mono_font = Font(name="Consolas", size=10)
    mono_bold = Font(name="Consolas", size=10, bold=True)

    # Feuille 1 : Dynamiques
    ws = wb.active
    ws.title = "Tags Dynamiques (DYN)"
    headers = ["Tag", "Couleur (hex)", "Rule Type", "Valeur à saisir"]
    for i, h in enumerate(headers, 1):
        c = ws.cell(row=1, column=i, value=h)
        c.font = header_font
        c.fill = header_fill
        c.alignment = Alignment(horizontal="center", vertical="center")
        c.border = border

    for idx, (tag, rule, value, color) in enumerate(TAGS, start=2):
        ws.cell(row=idx, column=1, value=tag).font = mono_bold
        col_cell = ws.cell(row=idx, column=2, value=f"#{color}")
        col_cell.font = Font(color="FFFFFF", size=10)
        col_cell.fill = PatternFill(start_color=color, end_color=color, fill_type="solid")
        col_cell.alignment = Alignment(horizontal="center")
        ws.cell(row=idx, column=3, value=rule)
        val_cell = ws.cell(row=idx, column=4, value=value)
        val_cell.font = mono_font
        val_cell.alignment = Alignment(wrap_text=True, vertical="top")
        for col in range(1, 5):
            ws.cell(row=idx, column=col).border = border

    widths = [14, 14, 22, 90]
    for i, w in enumerate(widths, 1):
        ws.column_dimensions[get_column_letter(i)].width = w
    ws.row_dimensions[1].height = 22
    ws.freeze_panes = "A2"

    # Feuille 2 : Statiques manuels
    ws2 = wb.create_sheet("Tags Statiques (STAT)")
    headers2 = ["Tag", "Couleur (hex)", "Signification / Action"]
    for i, h in enumerate(headers2, 1):
        c = ws2.cell(row=1, column=i, value=h)
        c.font = header_font
        c.fill = header_fill
        c.alignment = Alignment(horizontal="center", vertical="center")
        c.border = border

    for idx, (tag, desc, color) in enumerate(STATIC_MANUAL, start=2):
        ws2.cell(row=idx, column=1, value=tag).font = mono_bold
        col_cell = ws2.cell(row=idx, column=2, value=f"#{color}")
        col_cell.font = Font(color="FFFFFF", size=10)
        col_cell.fill = PatternFill(start_color=color, end_color=color, fill_type="solid")
        col_cell.alignment = Alignment(horizontal="center")
        ws2.cell(row=idx, column=3, value=desc)
        for col in range(1, 4):
            ws2.cell(row=idx, column=col).border = border

    for i, w in enumerate([14, 14, 80], 1):
        ws2.column_dimensions[get_column_letter(i)].width = w
    ws2.freeze_panes = "A2"

    # Feuille 3 : Prefixes
    ws3 = wb.create_sheet("Prefixes manuels")
    for i, h in enumerate(["Prefixe", "Description"], 1):
        c = ws3.cell(row=1, column=i, value=h)
        c.font = header_font
        c.fill = header_fill
        c.alignment = Alignment(horizontal="center")
        c.border = border
    for idx, (p, d) in enumerate(PREFIXES, start=2):
        ws3.cell(row=idx, column=1, value=p).font = mono_bold
        ws3.cell(row=idx, column=2, value=d)
    ws3.column_dimensions["A"].width = 14
    ws3.column_dimensions["B"].width = 70

    wb.save(out)
    print(f"[OK] Genere: {out.resolve()}")


if __name__ == "__main__":
    main()
