"""Biến riêng cho từng thiết bị từ CSV/Excel: mỗi dòng một thiết bị (cột 'device' = tên hoặc IP), các cột còn lại là biến của tác vụ."""
from __future__ import annotations

import csv
from pathlib import Path

KEY_COLUMNS = ("device", "name", "ip", "thiet_bi", "thiết bị", "host", "hostname")


def _read(path: Path) -> list[dict]:
    p = Path(path)
    if p.suffix.lower() in (".xlsx", ".xlsm"):
        import openpyxl
        rows = list(openpyxl.load_workbook(p, read_only=True, data_only=True).active.iter_rows(values_only=True))
        if not rows:
            return []
        head = [str(c or "").strip() for c in rows[0]]
        return [{head[i]: ("" if v is None else str(v)).strip() for i, v in enumerate(r) if i < len(head) and head[i]} for r in rows[1:]]
    with open(p, newline="", encoding="utf-8-sig") as fh:
        sample = fh.read(2048)
        fh.seek(0)
        delim = ";" if sample.count(";") > sample.count(",") else ","
        return [{(k or "").strip(): (v or "").strip() for k, v in row.items() if k} for row in csv.DictReader(fh, delimiter=delim)]


def load_table(path: Path | str) -> dict[str, dict[str, str]]:
    """{khóa_thiết_bị (tên hoặc IP, viết thường): {biến: giá_trị}}. Giữ nguyên chữ hoa/thường của tên biến."""
    out: dict[str, dict[str, str]] = {}
    for row in _read(Path(path)):
        low = {k.lower(): k for k in row}
        keycol = next((low[k] for k in KEY_COLUMNS if k in low), None)
        if not keycol or not row.get(keycol):
            continue
        vars_ = {k: v for k, v in row.items() if k != keycol and v != ""}
        out[row[keycol].strip().lower()] = vars_
        if "ip" in low and row.get(low["ip"]) and low["ip"] != keycol:
            out[row[low["ip"]].strip().lower()] = vars_
    return out


def lookup(table: dict, device: dict) -> dict[str, str]:
    if not table:
        return {}
    return table.get(str(device.get("name", "")).strip().lower()) or table.get(str(device.get("ip", "")).strip().lower()) or {}


def write_template(path: Path | str, devices: list[dict], fields: list[dict], current: dict | None = None) -> None:
    """Tạo file mẫu: cột device + các biến của tác vụ, mỗi thiết bị một dòng (điền sẵn giá trị đang nhập)."""
    cur = current or {}
    names = [f["name"] for f in fields]
    p = Path(path)
    rows = [[d["name"]] + [str(cur.get(n, f.get("default", "")) if not isinstance(cur.get(n, ""), bool) else str(cur.get(n)).lower())
                           for n, f in zip(names, fields)] for d in devices]
    if p.suffix.lower() == ".xlsx":
        import openpyxl
        wb = openpyxl.Workbook()
        ws = wb.active
        ws.append(["device"] + names)
        for r in rows:
            ws.append(r)
        wb.save(p)
    else:
        with open(p, "w", newline="", encoding="utf-8-sig") as fh:
            w = csv.writer(fh)
            w.writerow(["device"] + names)
            w.writerows(rows)
