import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

from textiletag import encode, decode, validate, describe, encode_flags, decode_flags, TextileTagError
import pytest


def test_encode():
    code = encode(
        garment_type="TP", material="CO", wash="N", temp="C",
        dry="T", color="W", size="3", iron=1, bleach=2,
        dryclean=0, country="US",
    )
    assert code == "01TPCONCTW3AUS"


def test_decode():
    result = decode("01TPCONCTW3AUS")
    assert result["garment_type"] == "TP"
    assert result["garment_type_label"] == "Top"
    assert result["material"] == "CO"
    assert result["material_label"] == "Cotton"
    assert result["wash"] == "N"
    assert result["wash_label"] == "Normal"
    assert result["temp"] == "C"
    assert result["dry"] == "T"
    assert result["color"] == "W"
    assert result["size"] == "3"
    assert result["size_label"] == "M"
    assert result["iron"] == 1
    assert result["bleach"] == 2
    assert result["dryclean"] == 0
    assert result["country"] == "US"


def test_validate_valid():
    errors = validate("01TPCONCTW3AUS")
    assert errors == []


def test_validate_invalid_length():
    errors = validate("INVALID")
    assert len(errors) > 0
    assert "14 characters" in errors[0]


def test_validate_bad_version():
    errors = validate("00TPCONCTW3AUS")
    assert any("reserved" in e for e in errors)


def test_validate_unknown_type():
    errors = validate("01ZZCONCTW3AUS")
    assert any("garment type" in e for e in errors)


def test_describe():
    desc = describe("01TPCONCTW3AUS")
    assert "cotton" in desc.lower()
    assert "top" in desc.lower()
    assert "US" in desc


def test_flags_roundtrip():
    for iron in range(4):
        for bleach in range(3):
            for dc in range(2):
                ch = encode_flags(iron, bleach, dc)
                result = decode_flags(ch)
                assert result["iron"] == iron
                assert result["bleach"] == bleach
                assert result["dryclean"] == dc


def test_encode_invalid_type():
    with pytest.raises(TextileTagError):
        encode(
            garment_type="ZZ", material="CO", wash="N", temp="C",
            dry="T", color="W", size="3", iron=1, bleach=2,
            dryclean=0, country="US",
        )


def test_decode_invalid():
    with pytest.raises(TextileTagError):
        decode("INVALID")


def test_case_insensitive_decode():
    result = decode("01tpconctw3aus")
    assert result["garment_type"] == "TP"


def test_spaces_stripped():
    result = decode("01 TP CO N C T W 3 A US")
    assert result["code"] == "01TPCONCTW3AUS"
