"""Data export utilities."""

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

from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill


def _ensure_project_path(filepath: str | Path) -> Path:
    """Ensure file is saved to project folder."""
    path = Path(filepath)
    # If path is relative or in temp, save to project folder
    if str(path).startswith('/tmp/') or not path.is_absolute():
        from datetime import datetime
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = path.name if path.name else f"export_{timestamp}{path.suffix if path.suffix else '.json'}"
        path = Path(f"/mnt/fnos/SurfAI/项目文件/导出数据/{filename}")
    return path


def export_json(data: Any, filepath: str | Path) -> Path:
    """
    Export data to JSON file.
    
    Args:
        data: Data to export
        filepath: Output file path
        
    Returns:
        Path to exported file
    """
    path = _ensure_project_path(filepath)
    path.parent.mkdir(parents=True, exist_ok=True)
    
    with open(path, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    
    return path


def export_csv(data: list[dict], filepath: str | Path) -> Path:
    """
    Export data to CSV file.
    
    Args:
        data: List of dictionaries
        filepath: Output file path
        
    Returns:
        Path to exported file
    """
    path = _ensure_project_path(filepath)
    path.parent.mkdir(parents=True, exist_ok=True)
    
    if not data:
        # Create empty file with headers
        with open(path, "w", encoding="utf-8", newline="") as f:
            f.write("")
        return path
    
    # Get headers from first row
    headers = list(data[0].keys())
    
    with open(path, "w", encoding="utf-8", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=headers)
        writer.writeheader()
        writer.writerows(data)
    
    return path


def export_txt(data: str, filepath: str | Path) -> Path:
    """
    Export text data to file.
    
    Args:
        data: Text to export
        filepath: Output file path
        
    Returns:
        Path to exported file
    """
    path = Path(filepath)
    path.parent.mkdir(parents=True, exist_ok=True)
    
    with open(path, "w", encoding="utf-8") as f:
        f.write(data)
    
    return path


def export_excel(data: list[dict], filepath: str | Path, sheet_name: str = "Data") -> Path:
    """
    Export data to Excel file.

    Args:
        data: List of dictionaries
        filepath: Output file path
        sheet_name: Name of the worksheet

    Returns:
        Path to exported file
    """
    path = _ensure_project_path(filepath)
    path.parent.mkdir(parents=True, exist_ok=True)
    
    wb = Workbook()
    ws = wb.active
    ws.title = sheet_name
    
    if not data:
        wb.save(path)
        return path
    
    # Get headers from first row
    headers = list(data[0].keys())
    
    # Write headers with styling
    header_fill = PatternFill(start_color="366092", end_color="366092", fill_type="solid")
    header_font = Font(bold=True, color="FFFFFF")
    
    for col_idx, header in enumerate(headers, 1):
        cell = ws.cell(row=1, column=col_idx, value=header)
        cell.fill = header_fill
        cell.font = header_font
    
    # Write data
    for row_idx, row_data in enumerate(data, 2):
        for col_idx, header in enumerate(headers, 1):
            value = row_data.get(header, "")
            ws.cell(row=row_idx, column=col_idx, value=value)
    
    # Auto-adjust column widths
    for col_idx, header in enumerate(headers, 1):
        max_length = len(str(header))
        for row in data:
            cell_value = str(row.get(header, ""))
            max_length = max(max_length, len(cell_value))
        ws.column_dimensions[ws.cell(row=1, column=col_idx).column_letter].width = min(max_length + 2, 50)
    
    wb.save(path)
    return path


def auto_export(data: Any, filepath: str | Path) -> Path:
    """
    Automatically choose export format based on data type and file extension.
    
    Args:
        data: Data to export
        filepath: Output file path
        
    Returns:
        Path to exported file
    """
    path = Path(filepath)
    suffix = path.suffix.lower()
    
    if suffix == ".json":
        return export_json(data, filepath)
    elif suffix == ".csv":
        if isinstance(data, list) and data and isinstance(data[0], dict):
            return export_csv(data, filepath)
        else:
            # Convert to list of dicts or export as JSON
            return export_json(data, filepath)
    elif suffix == ".xlsx":
        if isinstance(data, list) and data and isinstance(data[0], dict):
            return export_excel(data, filepath)
        else:
            return export_json(data, filepath)
    elif suffix == ".txt":
        if isinstance(data, str):
            return export_txt(data, filepath)
        else:
            return export_txt(json.dumps(data, ensure_ascii=False, indent=2), filepath)
    else:
        # Default to JSON
        return export_json(data, filepath)
