"""Shared helpers for the cli115 client implementations."""

from __future__ import annotations

from datetime import datetime

from cli115.client.models import Directory, File


def parse_ts(value) -> datetime | None:
    if not value:
        return None
    try:
        return datetime.fromtimestamp(int(value))
    except (ValueError, TypeError, OSError):
        pass
    if isinstance(value, str):
        for fmt in ("%Y-%m-%d %H:%M", "%Y-%m-%d %H:%M:%S"):
            try:
                return datetime.strptime(value, fmt)
            except ValueError:
                continue
    return None


def parse_labels(fl) -> list[str]:
    if not fl or not isinstance(fl, list):
        return []
    names: list[str] = []
    for item in fl:
        if isinstance(item, dict) and "name" in item:
            names.append(item["name"])
        elif isinstance(item, str):
            names.append(item)
    return names


def parse_item(item: dict) -> Directory | File:
    kwargs = {
        "id": str(item["fid"]) if "fid" in item else str(item["cid"]),
        "parent_id": str(item.get("cid" if "fid" in item else "pid", "")),
        "name": item.get("n", ""),
        "path": None,  # it is a attribute defined in our project
        "pickcode": item.get("pc", ""),
        "created_time": parse_ts(item.get("tp")),
        "modified_time": parse_ts(item.get("te") or item.get("t")),
        "open_time": parse_ts(item.get("to")),
        "labels": parse_labels(item.get("fl")),
    }
    if "fid" in item:
        kwargs.update(
            {
                "size": int(item.get("s", 0)),
                "sha1": item.get("sha", ""),
                "file_type": item.get("ico", ""),
                "starred": bool(item.get("sta")),
            }
        )
        klass = File
    else:
        kwargs.update(
            {
                "file_count": int(item.get("fc", 0)),
            }
        )
        klass = Directory
    return klass(**kwargs)
