"""Integration tests for GEO-SEO Optimizer."""

import pytest

from src.content_generator.geo_optimizer import GEOOptimizer
from src.content_generator.seo_optimizer import SEOOptimizer
from src.keyword_research.analyzer import KeywordAnalyzer
from src.keyword_research.batch_processor import BatchProcessor
from src.keyword_research.google_planner import GoogleKeywordPlanner
from src.platform_adapter.base_adapter import BaseAdapter, PlatformContent
from src.platform_adapter.medium_adapter import MediumAdapter
from src.platform_adapter.twitter_adapter import TwitterAdapter


@pytest.mark.asyncio
async def test_keyword_to_content_workflow():
    """Test complete workflow from keyword research to content optimization."""
    # Step 1: Keyword research
    async with GoogleKeywordPlanner("test_key") as planner:
        keyword_data = await planner.get_keyword_data("seo tools")

    # Step 2: Analyze keyword
    analyzer = KeywordAnalyzer()
    score = analyzer.analyze(keyword_data)

    assert score.recommendation in ["high", "medium", "low"]

    # Step 3: Create optimized content
    content = f"Best {keyword_data.keyword} for 2024. These tools help with SEO."

    # Step 4: SEO optimization
    seo_opt = SEOOptimizer()
    seo_result = seo_opt.optimize(content, keyword_data.keyword, "Best SEO Tools")

    assert seo_result.score > 0
    assert seo_result.keyword_density > 0

    # Step 5: GEO optimization
    geo_opt = GEOOptimizer()
    geo_result = geo_opt.optimize(content)

    assert geo_result.score > 0
    assert geo_result.entity_density >= 0


@pytest.mark.asyncio
async def test_batch_keyword_processing():
    """Test batch processing workflow."""
    keywords = ["seo", "marketing", "content", "optimization"]

    async with GoogleKeywordPlanner("test_key") as planner:
        processor = BatchProcessor(planner, max_concurrent=2)
        results = await processor.process_with_progress(keywords)

    assert results["total"] == 4
    assert results["successful_count"] == 4
    assert results["failed_count"] == 0


@pytest.mark.asyncio
async def test_multi_platform_adaptation():
    """Test content adaptation to multiple platforms."""
    content = "This is a comprehensive guide to SEO. It covers everything you need to know."

    # Twitter adaptation
    twitter = TwitterAdapter()
    twitter_result = twitter.format_content(content)
    assert isinstance(twitter_result, PlatformContent)
    assert twitter_result.metadata.get("platform") == "twitter"

    # Twitter thread
    thread_result = twitter.format_content(content, format="thread")
    assert thread_result.metadata.get("is_thread") is True

    # Medium adaptation
    medium = MediumAdapter()
    medium_result = medium.format_content(content, title="SEO Guide")
    assert isinstance(medium_result, PlatformContent)
    assert medium_result.title is not None


@pytest.mark.asyncio
async def test_end_to_end_pipeline():
    """Test complete end-to-end pipeline."""
    # Keyword research
    async with GoogleKeywordPlanner("test_key") as planner:
        keywords_data = []
        for kw in ["seo tools", "marketing software"]:
            data = await planner.get_keyword_data(kw)
            keywords_data.append(data)

    # Analyze keywords
    analyzer = KeywordAnalyzer()
    best_keyword = None
    best_score = 0

    for data in keywords_data:
        score = analyzer.analyze(data)
        if score.overall_score > best_score:
            best_score = score.overall_score
            best_keyword = data

    assert best_keyword is not None

    # Generate content
    content = f"Comprehensive guide to {best_keyword.keyword}."

    # Optimize content
    seo_opt = SEOOptimizer()
    geo_opt = GEOOptimizer()

    seo_result = seo_opt.optimize(content, best_keyword.keyword, "Guide")
    geo_result = geo_opt.optimize(content)

    # Adapt to platform
    twitter = TwitterAdapter()
    adapted = twitter.format_content(content)

    assert seo_result.score > 0
    assert geo_result.score > 0
    assert adapted.body is not None


class TestPlatformAdapters:
    """Test platform adapters."""

    def test_base_adapter_abstract(self):
        """Test BaseAdapter is abstract."""
        with pytest.raises(TypeError):
            BaseAdapter()

    def test_twitter_adapter(self):
        """Test Twitter adapter."""
        adapter = TwitterAdapter()
        assert adapter.get_max_length() == 280

        # Single tweet
        result = adapter.format_content("Hello world!")
        assert isinstance(result, PlatformContent)

        # Thread
        long_content = "This is a long content. " * 20
        thread = adapter.format_content(long_content, format="thread")
        assert thread.metadata.get("is_thread") is True
        assert "tweet_count" in thread.metadata

    def test_twitter_truncate(self):
        """Test Twitter content truncation."""
        adapter = TwitterAdapter()
        long_text = "a" * 300
        truncated = adapter.truncate_content(long_text)
        assert len(truncated) <= 280

    def test_medium_adapter(self):
        """Test Medium adapter."""
        adapter = MediumAdapter()
        assert adapter.get_max_length() == 50000

        result = adapter.format_content("# Article\\n\\nContent here", title="Test")
        assert isinstance(result, PlatformContent)
        assert result.title == "Test"


class TestAnalyticsIntegration:
    """Test analytics integration."""

    def test_metrics_tracker(self):
        """Test metrics tracker."""
        from src.analytics.metrics_tracker import MetricsTracker

        tracker = MetricsTracker()
        assert tracker.db_path == "data/metrics.db"

    def test_geo_analyzer(self):
        """Test GEO analyzer."""
        from src.analytics.geo_analyzer import GEOAnalyzer

        analyzer = GEOAnalyzer()
        result = analyzer.analyze_geo_performance("Test content about AI.")
        assert "score" in result
        assert "entity_coverage" in result

    def test_reporter(self):
        """Test reporter."""
        from src.analytics.reporter import Reporter

        reporter = Reporter()
        html = reporter.generate_html_report({"data": "test"})
        assert "<html>" in html

        json_report = reporter.generate_json_report({"data": "test"})
        assert json_report == {"data": "test"}
