#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
測試匯入邏輯
"""

import os

import pandas as pd
import pytest

EXCEL_PATH = "/Users/ogt/Downloads/缺貨測試.xlsx"


@pytest.mark.skipif(not os.path.exists(EXCEL_PATH), reason="缺少本機測試 Excel 檔案")
def test_import_logic():
    df = pd.read_excel(EXCEL_PATH)
    row = df.iloc[0]

    date_value = row.get("當前日期")
    row_import_date = None
    if pd.notna(date_value) and isinstance(date_value, (int, float)):
        parsed_date = pd.to_datetime(date_value, unit="D", origin="1899-12-30", errors="coerce")
        if pd.notna(parsed_date):
            row_import_date = parsed_date.date()

    stockout_date_value = row.get("缺貨日期")
    stockout_date_obj = None
    if pd.notna(stockout_date_value) and isinstance(stockout_date_value, (int, float)):
        stockout_parsed = pd.to_datetime(stockout_date_value, unit="D", origin="1899-12-30", errors="coerce")
        if pd.notna(stockout_parsed):
            stockout_date_obj = stockout_parsed.date()

    record = {
        "import_date": row_import_date,
        "department": row.get("處別"),
        "section": row.get("科別"),
        "pm_name": row.get("PM姓名"),
        "zone_id": row.get("區ID"),
        "zone_name": row.get("區名稱"),
        "product_code": str(row.get("商品ID", "")).strip(),
        "product_name": str(row.get("商品名稱", "")).strip(),
        "product_spec": row.get("單品/組合商品"),
        "borrow_transfer": row.get("借採轉"),
        "sale_price": None,
        "cost_price": None,
        "vendor_code": str(row.get("來源供應商編號", "")).strip(),
        "vendor_name": str(row.get("來源供應商名稱", "")).strip(),
        "current_stock": row.get("商品可賣量"),
        "stockout_date": stockout_date_obj,
        "stockout_days": row.get("缺貨天數"),
        "monthly_sales_amount": row.get("缺貨商品前30天業績"),
        "monthly_sales_qty": row.get("最近30天銷售量"),
        "daily_avg_sales": None,
        "safe_stock_days": row.get("庫存水位"),
        "notes": None,
    }

    assert record["product_code"] != ""
    assert "product_name" in record
