from __future__ import annotations
import os
from pathlib import Path
import pandas as pd

# ---------------------------------------------
# Cross-platform paths (Windows & Linux/Mac)
# ---------------------------------------------
def resolve_data_root() -> Path:
    """
    Priority:
      1) Env var IDRAC_DATA_DIR (absolute/relative OK)
      2) nearest parent of this file that contains a 'data' folder
      3) ./data under current working directory
    """
    env = os.getenv("IDRAC_DATA_DIR")
    if env:
        return Path(env).expanduser().resolve()

    here = Path(__file__).resolve()
    for p in [here] + list(here.parents):
        if (p / "data").is_dir():
            return (p / "data").resolve()

    return (Path.cwd() / "data").resolve()


DATA_ROOT = resolve_data_root()

SERVER_LIST_DIR = DATA_ROOT / "server_list"
SERVER_LIST_FILE = SERVER_LIST_DIR / "server_list.txt"

MAC_TXT_DIR = DATA_ROOT / "repository" / "mac"
OUTPUT_XLSX = DATA_ROOT / "temp" / "staging" / "mac_info.xlsx"

# Ensure output directory exists
OUTPUT_XLSX.parent.mkdir(parents=True, exist_ok=True)

# ---------------------------------------------
# Helpers
# ---------------------------------------------
def read_lines_any_encoding(path: Path) -> list[str]:
    """Read a text file trying common encodings (handles Windows & UTF-8)."""
    encodings = ["utf-8-sig", "utf-8", "cp949", "euc-kr", "latin-1"]
    for enc in encodings:
        try:
            with path.open("r", encoding=enc, errors="strict") as f:
                return f.read().splitlines()
        except Exception:
            continue
    # last resort with replacement
    with path.open("r", encoding="utf-8", errors="replace") as f:
        return f.read().splitlines()

# ---------------------------------------------
# Load server list (file names without .txt)
# ---------------------------------------------
if not SERVER_LIST_FILE.is_file():
    raise FileNotFoundError(f"server_list.txt not found: {SERVER_LIST_FILE}")

file_names = read_lines_any_encoding(SERVER_LIST_FILE)

data_list: list[str] = []
index_list: list[int | str] = []

sequence_number = 1

for name in file_names:
    # normalize and skip blanks
    base = (name or "").strip()
    if not base:
        continue

    txt_path = MAC_TXT_DIR / f"{base}.txt"
    if not txt_path.is_file():
        # if a file is missing, keep row aligned with an empty line
        data_list.append("")
        index_list.append("")
        continue

    lines = read_lines_any_encoding(txt_path)
    for i, line in enumerate(lines):
        cleaned = (line or "").strip().upper()
        if cleaned:
            data_list.append(cleaned)
            if i == 0:  # first line is always the service tag
                index_list.append(sequence_number)
                sequence_number += 1
            else:
                index_list.append("")  # keep column blank if not service tag
        else:
            data_list.append("")
            index_list.append("")

print(f"Length of index_list: {len(index_list)}")
print(f"Length of data_list: {len(data_list)}")

# ---------------------------------------------
# Save to Excel
# ---------------------------------------------
df = pd.DataFrame({
    "Index": index_list,   # will be column A
    "Content": data_list,  # will be column B
})

# header=False to start at column A without headers, index=False to omit row numbers
df.to_excel(OUTPUT_XLSX, index=False, header=False)

print(f"Saved: {OUTPUT_XLSX}")
