from __future__ import annotations

import csv
import json
from pathlib import Path
from typing import Any, Dict, List

import openpyxl

from store_db.csv_safe import csv_safe_cell, csv_safe_rows
from store_customer_lib.common import parse_fields_json


def flatten_members(rows: List[dict], field_labels: Dict[str, str]) -> List[Dict[str, Any]]:
    out: List[Dict[str, Any]] = []
    for r in rows:
        row = {
            "会员ID": r.get("id"),
            "姓名": r.get("name"),
            "手机号": r.get("phone"),
            "生日": r.get("birthday"),
            "到期日": r.get("due_date"),
            "备注": r.get("note"),
            "标签": r.get("tags_json"),
        }
        fields = parse_fields_json(r.get("fields_json") or "{}")
        for fk, val in fields.items():
            row[field_labels.get(fk, fk)] = val
        if r.get("wallet"):
            row["余额"] = r["wallet"].get("balance")
        out.append(row)
    return out


def preview_markdown(rows: List[dict], field_labels: Dict[str, str], limit: int = 20) -> str:
    flat = flatten_members(rows[:limit], field_labels)
    if not flat:
        return "暂无会员数据。"
    headers = list(flat[0].keys())
    lines = [
        "| " + " | ".join(headers) + " |",
        "| " + " | ".join(["---"] * len(headers)) + " |",
    ]
    for row in flat:
        lines.append("| " + " | ".join(str(row.get(h, "") or "") for h in headers) + " |")
    return "\n".join(lines)


def export_rows(rows: List[Dict[str, Any]], output_path: str) -> Dict[str, Any]:
    path = Path(output_path)
    path.parent.mkdir(parents=True, exist_ok=True)
    suffix = path.suffix.lower()
    if suffix == ".csv":
        headers = _headers(rows)
        with path.open("w", encoding="utf-8-sig", newline="") as f:
            w = csv.DictWriter(f, fieldnames=headers)
            w.writeheader()
            w.writerows(csv_safe_rows(rows))
    elif suffix == ".xlsx":
        wb = openpyxl.Workbook()
        sheet = wb.active
        sheet.title = "会员数据"
        headers = _headers(rows)
        sheet.append(headers)
        for row in rows:
            sheet.append([csv_safe_cell(row.get(h, "")) for h in headers])
        wb.save(path)
    elif suffix == ".json":
        path.write_text(json.dumps(rows, ensure_ascii=False, indent=2), encoding="utf-8")
    else:
        raise ValueError("仅支持 .csv / .xlsx / .json")
    return {"output_path": str(path), "row_count": len(rows)}


def _headers(rows: List[Dict[str, Any]]) -> List[str]:
    seen = set()
    headers: List[str] = []
    for row in rows:
        for k in row:
            if k not in seen:
                seen.add(k)
                headers.append(k)
    return headers
