# -*- coding: utf-8 -*-
"""助教作废任务"""

import json

from .base_task import BaseTask, TaskContext
from loaders.facts.assistant_abolish import AssistantAbolishLoader
from models.parsers import TypeParser


class AssistantAbolishTask(BaseTask):
    """同步助教作废记录"""

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

    def extract(self, context: TaskContext) -> dict:
        params = self._merge_common_params(
            {
                "siteId": context.store_id,
                "startTime": TypeParser.format_timestamp(context.window_start, self.tz),
                "endTime": TypeParser.format_timestamp(context.window_end, self.tz),
            }
        )
        records, _ = self.api.get_paginated(
            endpoint="/AssistantPerformance/GetAbolitionAssistant",
            params=params,
            page_size=self.config.get("api.page_size", 200),
            data_path=("data",),
            list_key="abolitionAssistants",
        )
        return {"records": records}

    def transform(self, extracted: dict, context: TaskContext) -> dict:
        parsed, skipped = [], 0
        for raw in extracted.get("records", []):
            mapped = self._parse_record(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 = AssistantAbolishLoader(self.db)
        inserted, updated, loader_skipped = loader.upsert_records(transformed["records"])
        return {
            "fetched": transformed["fetched"],
            "inserted": inserted,
            "updated": updated,
            "skipped": transformed["skipped"] + loader_skipped,
            "errors": 0,
        }

    def _parse_record(self, raw: dict, store_id: int) -> dict | None:
        abolish_id = TypeParser.parse_int(raw.get("id"))
        if not abolish_id:
            self.logger.warning("跳过缺少作废ID的记录: %s", raw)
            return None

        return {
            "store_id": store_id,
            "abolish_id": abolish_id,
            "table_id": TypeParser.parse_int(raw.get("tableId")),
            "table_name": raw.get("tableName"),
            "table_area_id": TypeParser.parse_int(raw.get("tableAreaId")),
            "table_area": raw.get("tableArea"),
            "assistant_no": raw.get("assistantOn"),
            "assistant_name": raw.get("assistantName"),
            "charge_minutes": TypeParser.parse_int(raw.get("pdChargeMinutes")),
            "abolish_amount": TypeParser.parse_decimal(raw.get("assistantAbolishAmount")),
            "create_time": TypeParser.parse_timestamp(
                raw.get("createTime") or raw.get("create_time"), self.tz
            ),
            "trash_reason": raw.get("trashReason"),
            "raw_data": json.dumps(raw, ensure_ascii=False),
        }
