import pandas as pd
import pytest

from services.import_service import (
    _read_daily_sales_excel,
    _should_quarantine_failed_import,
)


def test_daily_sales_reader_prefers_detail_sheet_over_summary_sheets(tmp_path):
    workbook = tmp_path / "即時業績_當日.xlsx"
    with pd.ExcelWriter(workbook, engine="openpyxl") as writer:
        pd.DataFrame([
            [None, None, None, None],
            [None, None, None, None],
            ["列標籤", "加總 - 總業績", "加總 - 總成本", "加總 - 折扣金額"],
            ["保健", "100", "60", "5"],
        ]).to_excel(writer, sheet_name="工作表1", header=False, index=False)
        pd.DataFrame({
            "列標籤": ["A"],
            "商品名稱": ["彙總商品"],
            "銷售網頁ID": ["P001"],
            "加總 - 總業績": ["300"],
        }).to_excel(writer, sheet_name="工作表2", index=False)
        pd.DataFrame({
            "狀態": ["完成"],
            "日期": ["2026-06-14"],
            "商品ID": ["SKU001"],
            "商品名稱": ["專業測試商品"],
            "數量": ["1"],
            "總業績": ["1200"],
        }).to_excel(writer, sheet_name="即時業績明細", index=False)

    df, metadata = _read_daily_sales_excel(str(workbook))

    assert metadata["sheet_name"] == "即時業績明細"
    assert metadata["header_row"] == 1
    assert metadata["date_col"] == "日期"
    assert list(df["商品名稱"]) == ["專業測試商品"]


def test_daily_sales_reader_scans_header_rows(tmp_path):
    workbook = tmp_path / "header-offset.xlsx"
    with pd.ExcelWriter(workbook, engine="openpyxl") as writer:
        pd.DataFrame([
            ["報表產製時間", "2026-06-14", None],
            [None, None, None],
            ["日期", "商品名稱", "總業績"],
            ["2026-06-14", "測試商品", "999"],
        ]).to_excel(writer, sheet_name="即時業績明細", header=False, index=False)

    df, metadata = _read_daily_sales_excel(str(workbook))

    assert metadata["header_row"] == 3
    assert df.iloc[0]["商品名稱"] == "測試商品"


def test_daily_sales_reader_reports_checked_sheets_when_no_candidate(tmp_path):
    workbook = tmp_path / "invalid.xlsx"
    with pd.ExcelWriter(workbook, engine="openpyxl") as writer:
        pd.DataFrame({"Unnamed: 0": ["A"], "Unnamed: 1": ["B"]}).to_excel(
            writer,
            sheet_name="工作表1",
            index=False,
        )

    with pytest.raises(ValueError) as exc:
        _read_daily_sales_excel(str(workbook))

    assert "Excel 欄位防禦失敗" in str(exc.value)
    assert "工作表1" in str(exc.value)


def test_only_permanent_import_failures_are_quarantined():
    assert _should_quarantine_failed_import("Excel 欄位防禦失敗：缺少必要欄位分類")
    assert _should_quarantine_failed_import("Excel 日期防禦失敗：明細最大日期 2026-06-10")
    assert not _should_quarantine_failed_import("無法從 Google Drive 下載檔案")
