import csv
import os
from pathlib import Path
from openpyxl import Workbook
from openpyxl.utils import get_column_letter


def ensure_output_dir(root_dir: Path, output_dir_name: str) -> Path:
    out = root_dir / output_dir_name
    out.mkdir(parents=True, exist_ok=True)
    return out


def write_csv(csv_path: Path, rows: list[dict], columns: list[str]) -> None:
    # overwrite fully
    with csv_path.open("w", newline="", encoding="utf-8-sig") as f:
        writer = csv.DictWriter(f, fieldnames=columns)
        writer.writeheader()
        writer.writerows(rows)


def write_xlsx(xlsx_path: Path, rows: list[dict], columns: list[str], sheet_name: str = "tickets") -> None:
    wb = Workbook()
    ws = wb.active

    safe_sheet = (sheet_name or "tickets").replace("/", "-").replace("\\", "-").replace(":", "-")
    safe_sheet = safe_sheet[:31] if safe_sheet else "tickets"
    ws.title = safe_sheet

    ws.append(columns)
    for r in rows:
        ws.append([r.get(col, "") for col in columns])

    ws.freeze_panes = "A2"
    ws.auto_filter.ref = f"A1:{get_column_letter(len(columns))}{len(rows) + 1}"

    for col_idx, col_name in enumerate(columns, start=1):
        max_len = len(col_name)
        for row in rows:
            max_len = max(max_len, len(str(row.get(col_name, "") or "")))
        ws.column_dimensions[get_column_letter(col_idx)].width = min(max(max_len + 2, 10), 50)

    # overwrite fully
    wb.save(str(xlsx_path))

