"""Helpers for managing import template files used by administrators."""
from __future__ import annotations

import json
import os
from datetime import datetime, timezone
from typing import Any, Dict


PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
TEMPLATE_DIR = os.path.join(PROJECT_ROOT, "data", "template")
PERMIT_TEMPLATE_FILENAME = "风险提示表 模板.xlsx"
PERMIT_SAMPLE_FILENAME = "风险提示表(仅销售预包装食品备案，市场监管部门)（样表）.xlsx"
TEMPLATE_META_FILENAME = "template_meta.json"


def get_permit_template_path() -> str:
    """Return the absolute path to the permit import template."""
    return os.path.join(TEMPLATE_DIR, PERMIT_TEMPLATE_FILENAME)


def get_permit_sample_path() -> str:
    """Return the absolute path to the permit import sample file."""
    return os.path.join(TEMPLATE_DIR, PERMIT_SAMPLE_FILENAME)


def _meta_path() -> str:
    return os.path.join(TEMPLATE_DIR, TEMPLATE_META_FILENAME)


def _read_meta() -> Dict[str, Any]:
    path = _meta_path()
    if not os.path.exists(path):
        return {}
    try:
        with open(path, "r", encoding="utf-8") as meta_file:
            return json.load(meta_file)
    except (json.JSONDecodeError, OSError):
        return {}


def get_permit_template_metadata() -> Dict[str, Any]:
    """Return metadata for the permit template file (size, timestamps, uploader)."""
    template_path = get_permit_template_path()
    exists = os.path.exists(template_path)
    metadata = {
        "exists": exists,
        "filename": os.path.basename(template_path),
        "filesize": os.path.getsize(template_path) if exists else 0,
        "updated_at": None,
        "uploaded_by": None,
        "source_filename": None,
        "download_url": "/fs-ai-asistant/api/workflow/lawrisk/admin/permit-import/template",
    }
    meta_file_data = _read_meta()
    metadata.update({k: v for k, v in meta_file_data.items() if k in metadata or k in {"hash"} })
    if metadata.get("updated_at") and isinstance(metadata["updated_at"], (int, float)):
        metadata["updated_at"] = datetime.fromtimestamp(metadata["updated_at"], tz=timezone.utc).isoformat()
    return metadata


def overwrite_permit_template(file_bytes: bytes, filename: str, uploaded_by: str | None = None) -> Dict[str, Any]:
    """Overwrite the stored permit template with the uploaded bytes."""
    if not file_bytes:
        raise ValueError("模板文件内容不能为空")
    os.makedirs(TEMPLATE_DIR, exist_ok=True)
    target_path = get_permit_template_path()
    with open(target_path, "wb") as template_file:
        template_file.write(file_bytes)

    timestamp = datetime.now(tz=timezone.utc).isoformat()
    meta_payload = {
        "updated_at": timestamp,
        "uploaded_by": uploaded_by,
        "source_filename": filename,
        "filesize": len(file_bytes),
        "filename": os.path.basename(target_path),
    }
    with open(_meta_path(), "w", encoding="utf-8") as meta_file:
        json.dump(meta_payload, meta_file, ensure_ascii=False, indent=2)
    meta_payload["exists"] = True
    meta_payload["download_url"] = "/fs-ai-asistant/api/workflow/lawrisk/admin/permit-import/template"
    return meta_payload
