from __future__ import annotations

import csv
import json
from pathlib import Path
from typing import Any

import openpyxl


def flatten_customers(customers: list[dict[str, Any]]) -> list[dict[str, Any]]:
    rows: list[dict[str, Any]] = []
    for customer in customers:
        row = {
            "客户ID": customer["customer_id"],
            "姓名": customer.get("name"),
            "手机号": customer.get("primary_phone"),
            "生日": customer.get("birthday"),
            "标签": "，".join(customer.get("tags", [])),
            "备注": customer.get("notes"),
            "最近更新时间": customer.get("updated_at"),
        }
        for field_key, item in customer.get("dynamic_field_map", {}).items():
            row[item.get("label") or field_key] = item.get("displayValue") or item.get("value")
        rows.append(row)
    return rows


def export_customers(customers: list[dict[str, Any]], output_path: str | Path) -> dict[str, Any]:
    path = Path(output_path)
    path.parent.mkdir(parents=True, exist_ok=True)
    rows = flatten_customers(customers)
    if path.suffix.lower() == ".csv":
        _write_csv(rows, path)
    elif path.suffix.lower() == ".xlsx":
        _write_xlsx(rows, path)
    elif path.suffix.lower() == ".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 preview_as_markdown(customers: list[dict[str, Any]], limit: int = 20) -> str:
    rows = flatten_customers(customers)[:limit]
    if not rows:
        return "暂无客户数据。"
    headers = list(rows[0].keys())
    lines = [
        "| " + " | ".join(headers) + " |",
        "| " + " | ".join(["---"] * len(headers)) + " |",
    ]
    for row in rows:
        lines.append("| " + " | ".join(str(row.get(header, "") or "") for header in headers) + " |")
    return "\n".join(lines)


def _write_csv(rows: list[dict[str, Any]], path: Path) -> None:
    headers = _collect_headers(rows)
    with path.open("w", encoding="utf-8-sig", newline="") as file:
        writer = csv.DictWriter(file, fieldnames=headers)
        writer.writeheader()
        writer.writerows(rows)


def _write_xlsx(rows: list[dict[str, Any]], path: Path) -> None:
    workbook = openpyxl.Workbook()
    sheet = workbook.active
    sheet.title = "客户数据"
    headers = _collect_headers(rows)
    sheet.append(headers)
    for row in rows:
        sheet.append([row.get(header, "") for header in headers])
    workbook.save(path)


def _collect_headers(rows: list[dict[str, Any]]) -> list[str]:
    headers: list[str] = []
    seen: set[str] = set()
    for row in rows:
        for key in row.keys():
            if key not in seen:
                seen.add(key)
                headers.append(key)
    return headers
