import json


def test_offline_identity_audit_counts_current_matcher_outcomes():
    from scripts.audit_competitor_identity_jsonl import audit_rows

    rows = [
        {
            "sku": "OK-1",
            "momo_name": "理膚寶水 B5 修復霜 40ml",
            "competitor_product_name": "理膚寶水 全面修復霜 B5 40ml",
            "momo_price": 699,
            "pchome_price": 679,
            "is_expired": False,
        },
        {
            "sku": "BAD-1",
            "momo_name": "【蘭蔻】官方直營 玫瑰霜60ml+玫瑰精露150ml",
            "competitor_product_name": "LOREAL Paris 巴黎萊雅 金致臻顏花蜜奢養膠原輕盈乳霜_60ml",
            "momo_price": 18765,
            "pchome_price": 1249,
            "is_expired": False,
        },
        {
            "sku": "EXPIRED-BAD",
            "momo_name": "【蘭蔻】官方直營 玫瑰霜60ml+玫瑰精露150ml",
            "competitor_product_name": "LOREAL Paris 巴黎萊雅 金致臻顏花蜜奢養膠原輕盈乳霜_60ml",
            "momo_price": 18765,
            "pchome_price": 1249,
            "is_expired": True,
        },
    ]

    summary = audit_rows(rows, sample_limit=5)

    assert summary["scanned"] == 3
    assert summary["accepted_current"] == 1
    assert summary["veto_current"] == 2
    assert summary["expired"] == 1
    assert summary["fresh_veto_or_low"] == 1
    assert summary["samples"][0]["sku"] == "BAD-1"
    assert "brand_conflict" in summary["samples"][0]["reasons"]


def test_offline_identity_audit_cli_reads_jsonl(tmp_path, capsys):
    from scripts.audit_competitor_identity_jsonl import main

    path = tmp_path / "rows.jsonl"
    path.write_text(
        json.dumps({
            "sku": "OK-CLI",
            "momo_product_name": "理膚寶水 B5 修復霜 40ml",
            "best_competitor_product_name": "理膚寶水 全面修復霜 B5 40ml",
            "momo_price": 699,
            "best_competitor_price": 679,
        }, ensure_ascii=False)
        + "\n",
        encoding="utf-8",
    )

    assert main([str(path)]) == 0
    output = json.loads(capsys.readouterr().out)
    assert output["scanned"] == 1
    assert output["accepted_current"] == 1


def test_offline_identity_audit_script_stays_database_free():
    from pathlib import Path

    source = Path("scripts/audit_competitor_identity_jsonl.py").read_text(encoding="utf-8")
    assert "DatabaseManager" not in source
    assert "create_engine" not in source
    assert "psycopg" not in source
