import pytest
import json
import os
import sys
from unittest.mock import patch, MagicMock

# Add current dir to sys.path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import b2b_marketing_orchestrator as orchestrator

@pytest.fixture
def mock_gemini_response():
    return """## Schritt 1: Angebot (WAS)

Kurzresuemee:
* Test Summary 1
* Test Summary 2

| Produkt/Loesung | Beschreibung | Kernfunktionen | Differenzierung | Primaere Quelle (URL) |
|---|---|---|---|---|
| Test Bot | A great robot | AI | Faster | https://example.com/bot |
"""

@patch("b2b_marketing_orchestrator.load_api_key", return_value="fake_key")
@patch("b2b_marketing_orchestrator.get_text_from_url", return_value="<html><body>Test Content</body></html>")
@patch("b2b_marketing_orchestrator.find_relevant_links", return_value=[])
@patch("b2b_marketing_orchestrator.call_gemini_api")
def test_start_generation(mock_call, mock_links, mock_scrape, mock_key, mock_gemini_response):
    mock_call.return_value = mock_gemini_response
    
    result = orchestrator.start_generation("https://example.com", "de", "DACH", "Cleaning")
    
    assert "offer" in result
    assert result["offer"]["headers"] == ["Produkt/Loesung", "Beschreibung", "Kernfunktionen", "Differenzierung", "Primaere Quelle (URL)"]
    assert len(result["offer"]["rows"]) == 1
    assert result["offer"]["rows"][0][0] == "Test Bot"
    # Note: Orchestrator uses a hardcoded summary for Step 1 in its return dict
    assert "Angebotsanalyse" in result["offer"]["summary"][0]

def test_parse_markdown_table():
    md = """
| Header 1 | Header 2 |
|---|---|
| Val 1 | Val 2 |
"""
    result = orchestrator.parse_markdown_table(md)
    assert result["headers"] == ["Header 1", "Header 2"]
    assert result["rows"] == [["Val 1", "Val 2"]]

@patch("b2b_marketing_orchestrator.load_api_key", return_value="fake_key")
@patch("b2b_marketing_orchestrator.call_gemini_api", return_value="Test Product, Nice Bot, AI, Best, https://test.com")
def test_enrich_product(mock_call, mock_key):
    result = orchestrator.enrich_product("Test Product", "https://test.com", "de")
    assert len(result) == 5
    assert result[0] == "Test Product"
    assert result[1] == "Nice Bot"
