"""The two suggestion decision values move to rian's words by a backfill, never in a migration
(Stream K1, rename map row 6): `merged` -> `same`, `kept_apart` -> `separate`; idempotent."""
from sqlalchemy import create_engine, select
from sqlalchemy.orm import Session
from sqlalchemy.pool import StaticPool

from app import cli
from app.models import Account, Base, Brand, ProductLine, ProductVariant, Suggestion


def _db() -> Session:
    engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
    Base.metadata.create_all(engine, tables=[Account.__table__, Suggestion.__table__])
    return Session(engine)


def test_the_two_old_values_become_the_two_words_and_a_second_run_changes_nothing():
    db = _db()
    db.add_all([
        Suggestion(level="product", left_id=1, right_id=2, reason="key", decision="merged"),
        Suggestion(level="product", left_id=3, right_id=4, reason="key", decision="kept_apart"),
        Suggestion(level="brand", left_id=5, right_id=6, reason="key", decision="superseded"),
        Suggestion(level="line", left_id=7, right_id=8, reason="key", decision=None),
    ])
    db.commit()
    assert cli.backfill_suggestion_decisions(db) == "suggestion decisions: 1 merged -> same, 1 kept_apart -> separate"
    assert sorted(v or "" for v in db.scalars(select(Suggestion.decision))) == ["", "same", "separate", "superseded"]
    assert cli.backfill_suggestion_decisions(db) == "suggestion decisions: 0 merged -> same, 0 kept_apart -> separate"
    assert "suggestion_decisions" in cli.BACKFILLS


def test_the_attribute_keys_move_value_for_value_and_a_second_run_changes_nothing():
    db = _db()
    Base.metadata.create_all(db.get_bind(), tables=[Brand.__table__, ProductLine.__table__, ProductVariant.__table__])
    db.add_all([
        ProductVariant(id=1, name="1 Million Elixir 100ml", match_key="k1", attributes={"variation": "elixir", "variation_kind": "concentration", "concentration": "parfum"}),
        ProductVariant(id=2, name="Rouge Allure 99", match_key="k2", attributes={"variation": "99 pirate", "variation_kind": "color"}),
        ProductVariant(id=3, name="Blue Label 1L", match_key="k3", attributes={"abv": "40"}),
        ProductVariant(id=4, name="Bare", match_key="k4", attributes=None),
    ])
    db.commit()
    assert cli.backfill_attribute_keys(db) == "attribute keys: 2 variant(s) moved from variation/variation_kind to attribute/attribute_kind"
    assert db.get(ProductVariant, 1).attributes == {"attribute": "elixir", "attribute_kind": "concentration", "concentration": "parfum"}
    assert db.get(ProductVariant, 2).attributes == {"attribute": "99 pirate", "attribute_kind": "color"}
    assert db.get(ProductVariant, 3).attributes == {"abv": "40"}
    assert cli.backfill_attribute_keys(db) == "attribute keys: 0 variant(s) moved from variation/variation_kind to attribute/attribute_kind"
    assert "attribute_keys" in cli.BACKFILLS
