"""Tests para validate_recipe_yaml."""
import sys
import os

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

from core.validate_recipe_yaml import validate_recipe_yaml

VALID_YAML = """
name: product_list
url_pattern: 'https://shop\\.example\\.com/.*'
steps:
  - wait_selector: ".product-card"
  - js: "document.querySelector('.price').innerText"
output:
  sink: stdout
"""


def test_recipe_valida_minima_retorna_valid_true():
    result = validate_recipe_yaml(VALID_YAML)
    assert result["valid"] is True
    assert result["errors"] == []
    assert isinstance(result["parsed"], dict)
    assert result["parsed"]["name"] == "product_list"


def test_name_ausente_produce_error():
    yaml_text = """
url_pattern: "https://example.com"
steps:
  - js: "1+1"
"""
    result = validate_recipe_yaml(yaml_text)
    assert result["valid"] is False
    assert any("name" in e for e in result["errors"])


def test_url_pattern_invalido_produce_error():
    yaml_text = """
name: my_recipe
url_pattern: "[invalid("
steps:
  - js: "1"
"""
    result = validate_recipe_yaml(yaml_text)
    assert result["valid"] is False
    assert any("url_pattern" in e for e in result["errors"])


def test_step_sin_js_ni_wait_selector_produce_error():
    yaml_text = """
name: bad_steps
url_pattern: "https://example.com"
steps:
  - description: "solo descripcion sin accion"
"""
    result = validate_recipe_yaml(yaml_text)
    assert result["valid"] is False
    assert any("js" in e or "wait_selector" in e for e in result["errors"])


def test_sink_invalido_produce_error():
    yaml_text = """
name: bad_sink
url_pattern: "https://example.com"
steps:
  - js: "1"
output:
  sink: invalid_sink
"""
    result = validate_recipe_yaml(yaml_text)
    assert result["valid"] is False
    assert any("sink" in e for e in result["errors"])


def test_name_no_snake_case_produce_error():
    yaml_text = """
name: MyRecipe
url_pattern: "https://example.com"
steps:
  - js: "1"
"""
    result = validate_recipe_yaml(yaml_text)
    assert result["valid"] is False
    assert any("snake_case" in e for e in result["errors"])


def test_output_schema_valido():
    yaml_text = """
name: with_schema
url_pattern: "https://example.com"
steps:
  - js: "1"
output:
  sink: stdout
  schema:
    - field: price
      type: float
    - field: name
      type: string
"""
    result = validate_recipe_yaml(yaml_text)
    assert result["valid"] is True


if __name__ == "__main__":
    test_recipe_valida_minima_retorna_valid_true()
    test_name_ausente_produce_error()
    test_url_pattern_invalido_produce_error()
    test_step_sin_js_ni_wait_selector_produce_error()
    test_sink_invalido_produce_error()
    test_name_no_snake_case_produce_error()
    test_output_schema_valido()
    print("All tests passed.")
