"""Tests for the Export plugin."""

from __future__ import annotations

import json

import pytest

from agent_scout.plugins.exporter import ExporterPlugin


@pytest.fixture
def sample_data():
    return {
        "title": "Flight Comparison",
        "summary": "Found 3 flights from NYC to London",
        "results": [
            {"name": "British Airways", "value": "$450"},
            {"name": "United", "value": "$520"},
        ],
        "comparison_table": [
            {"airline": "BA", "price": 450, "stops": 0},
            {"airline": "UA", "price": 520, "stops": 1},
            {"airline": "AA", "price": 480, "stops": 0},
        ],
        "steps": ["Searched web for flights", "Compared prices", "Identified best option"],
    }


async def test_export_json(sample_data):
    plugin = ExporterPlugin()
    result = await plugin.execute("export", {"format": "json", "data": sample_data})
    parsed = json.loads(result)
    assert parsed["title"] == "Flight Comparison"
    assert len(parsed["comparison_table"]) == 3


async def test_export_markdown(sample_data):
    plugin = ExporterPlugin()
    result = await plugin.execute("export", {"format": "markdown", "data": sample_data})
    assert "# Flight Comparison" in result
    assert "## Summary" in result
    assert "## Results" in result
    assert "## Comparison" in result
    assert "BA" in result
    assert "## Steps Taken" in result


async def test_export_csv(sample_data):
    plugin = ExporterPlugin()
    result = await plugin.execute("export", {"format": "csv", "data": sample_data})
    assert "airline" in result
    assert "BA" in result
    assert "520" in result


async def test_export_html(sample_data):
    plugin = ExporterPlugin()
    result = await plugin.execute("export", {"format": "html", "data": sample_data})
    assert "<!DOCTYPE html>" in result
    assert "<title>Flight Comparison</title>" in result
    assert "<table>" in result
    assert "BA" in result
    assert "AgentScout" in result


async def test_export_to_file(sample_data, tmp_path):
    plugin = ExporterPlugin()
    path = str(tmp_path / "report.json")
    result = await plugin.execute(
        "export", {"format": "json", "data": sample_data, "save_path": path}
    )
    assert "Exported to" in result

    with open(path) as f:
        parsed = json.loads(f.read())
    assert parsed["title"] == "Flight Comparison"


async def test_export_unsupported_format():
    plugin = ExporterPlugin()
    result = await plugin.execute("export", {"format": "xml", "data": {"key": "val"}})
    assert "Unsupported format" in result


async def test_export_empty_data():
    plugin = ExporterPlugin()
    result = await plugin.execute("export", {"format": "json", "data": {}})
    assert "Error" in result


async def test_export_string_data():
    """Data passed as a JSON string should be parsed."""
    plugin = ExporterPlugin()
    result = await plugin.execute("export", {"format": "json", "data": '{"title": "Test"}'})
    parsed = json.loads(result)
    assert parsed["title"] == "Test"


async def test_export_invalid_json_string():
    plugin = ExporterPlugin()
    result = await plugin.execute("export", {"format": "json", "data": "not json"})
    assert "Invalid JSON" in result


async def test_unknown_tool():
    plugin = ExporterPlugin()
    result = await plugin.execute("unknown", {})
    assert "Unknown tool" in result


async def test_get_tools():
    plugin = ExporterPlugin()
    tools = plugin.get_tools()
    assert len(tools) == 1
    assert tools[0].name == "export"


async def test_md_alias():
    """'md' should work as alias for 'markdown'."""
    plugin = ExporterPlugin()
    result = await plugin.execute(
        "export", {"format": "md", "data": {"title": "Test", "summary": "Hello"}}
    )
    assert "# Test" in result


async def test_csv_with_flat_results():
    """CSV with flat list (non-dict) results."""
    plugin = ExporterPlugin()
    result = await plugin.execute(
        "export",
        {"format": "csv", "data": {"results": ["apple", "banana", "cherry"]}},
    )
    assert "apple" in result
    assert "banana" in result


async def test_html_with_dict_results():
    plugin = ExporterPlugin()
    result = await plugin.execute(
        "export",
        {"format": "html", "data": {"title": "Test", "results": {"key": "value"}}},
    )
    assert "<strong>key</strong>" in result
    assert "value" in result
