"""Data export — export Odoo records as CSV or JSON."""

import csv
import json
from pathlib import Path

from cli_anything.odoo_12.utils.odoo_backend import OdooBackend
from cli_anything.odoo_12.core.record import parse_domain, parse_fields


def export_csv(rpc: OdooBackend, model: str, output_path: str,
               fields_str: str = "", domain_str: str = "[]",
               limit: int = 0, order: str = "") -> dict:
    """Export records to CSV file."""
    domain = parse_domain(domain_str)
    fields = parse_fields(fields_str)

    if not fields:
        field_defs = rpc.fields_get(model, attributes=["type", "string"])
        fields = [
            k for k, v in field_defs.items()
            if v.get("type") not in ("binary", "one2many", "many2many")
        ][:20]  # Limit default fields

    records = rpc.search_read(model, domain, fields=fields,
                              limit=limit, order=order)

    Path(output_path).parent.mkdir(parents=True, exist_ok=True)
    with open(output_path, "w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=fields, extrasaction="ignore")
        writer.writeheader()
        for rec in records:
            row = {}
            for field in fields:
                val = rec.get(field, "")
                if isinstance(val, (list, tuple)) and len(val) == 2:
                    val = val[1]  # Many2one: (id, name) -> name
                elif isinstance(val, bool):
                    val = str(val)
                row[field] = val
            writer.writerow(row)

    return {
        "model": model,
        "output": output_path,
        "format": "csv",
        "record_count": len(records),
        "fields": fields,
    }


def export_json(rpc: OdooBackend, model: str, output_path: str | None = None,
                fields_str: str = "", domain_str: str = "[]",
                limit: int = 0, order: str = "") -> dict:
    """Export records as JSON."""
    domain = parse_domain(domain_str)
    fields = parse_fields(fields_str)

    records = rpc.search_read(model, domain, fields=fields,
                              limit=limit, order=order)

    data = {
        "model": model,
        "record_count": len(records),
        "records": records,
    }

    if output_path:
        Path(output_path).parent.mkdir(parents=True, exist_ok=True)
        with open(output_path, "w", encoding="utf-8") as f:
            json.dump(data, f, indent=2, default=str, ensure_ascii=False)
        data["output"] = output_path
        data["format"] = "json"

    return data
