# -*- coding: utf-8 -*-
"""台桌档案任务"""

import json

from .base_task import BaseTask, TaskContext
from loaders.dimensions.table import TableLoader
from models.parsers import TypeParser


class TablesTask(BaseTask):
    """同步门店台桌列表"""

    def get_task_code(self) -> str:
        return "TABLES"

    def extract(self, context: TaskContext) -> dict:
        params = self._merge_common_params({"siteId": context.store_id})
        records, _ = self.api.get_paginated(
            endpoint="/Table/GetSiteTables",
            params=params,
            page_size=self.config.get("api.page_size", 200),
            data_path=("data",),
            list_key="siteTables",
        )
        return {"records": records}

    def transform(self, extracted: dict, context: TaskContext) -> dict:
        parsed, skipped = [], 0
        for raw in extracted.get("records", []):
            mapped = self._parse_table(raw, context.store_id)
            if mapped:
                parsed.append(mapped)
            else:
                skipped += 1
        return {
            "records": parsed,
            "fetched": len(extracted.get("records", [])),
            "skipped": skipped,
        }

    def load(self, transformed: dict, context: TaskContext) -> dict:
        loader = TableLoader(self.db)
        inserted, updated, loader_skipped = loader.upsert_tables(transformed["records"])
        return {
            "fetched": transformed["fetched"],
            "inserted": inserted,
            "updated": updated,
            "skipped": transformed["skipped"] + loader_skipped,
            "errors": 0,
        }

    def _parse_table(self, raw: dict, store_id: int) -> dict | None:
        table_id = TypeParser.parse_int(raw.get("id"))
        if not table_id:
            self.logger.warning("跳过缺少 table_id 的台桌记录: %s", raw)
            return None

        return {
            "store_id": store_id,
            "table_id": table_id,
            "site_id": TypeParser.parse_int(raw.get("site_id") or raw.get("siteId")),
            "area_id": TypeParser.parse_int(
                raw.get("site_table_area_id") or raw.get("siteTableAreaId")
            ),
            "area_name": raw.get("areaName") or raw.get("site_table_area_name"),
            "table_name": raw.get("table_name") or raw.get("tableName"),
            "table_price": TypeParser.parse_decimal(
                raw.get("table_price") or raw.get("tablePrice")
            ),
            "table_status": raw.get("table_status") or raw.get("tableStatus"),
            "table_status_name": raw.get("tableStatusName"),
            "light_status": raw.get("light_status"),
            "is_rest_area": raw.get("is_rest_area"),
            "show_status": raw.get("show_status"),
            "virtual_table": raw.get("virtual_table"),
            "charge_free": raw.get("charge_free"),
            "only_allow_groupon": raw.get("only_allow_groupon"),
            "is_online_reservation": raw.get("is_online_reservation"),
            "created_time": TypeParser.parse_timestamp(
                raw.get("create_time") or raw.get("createTime"), self.tz
            ),
            "raw_data": json.dumps(raw, ensure_ascii=False),
        }
