#!/usr/bin/env python3
"""Test script for new optimization features."""
import sys
from pathlib import Path

# Add project root to Python path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

import asyncio
from loguru import logger

async def test_grammar_checker():
    """Test grammar checker."""
    logger.info("Testing Grammar Checker...")
    try:
        from src.agents.grammar_checker import GrammarCheckAgent

        checker = GrammarCheckAgent()

        # Test with correct text
        result1 = await checker.process("Ich habe einen guten Text geschrieben.")
        logger.info(f"  Correct text: {result1['error_count']} errors")

        # Test with error
        result2 = await checker.process("Ich habe ein Fehler gemacht.")
        logger.info(f"  Text with error: {result2['error_count']} errors")

        logger.success("✅ Grammar Checker working!")
        return True
    except Exception as e:
        logger.error(f"❌ Grammar Checker failed: {e}")
        return False

async def test_style_validator():
    """Test style validator."""
    logger.info("Testing Style Validator...")
    try:
        from src.agents.style_validator import StyleValidator

        validator = StyleValidator()

        # Test similarity
        result = await validator.process(
            generated_text="Das ist ein Test-Post über Business.",
            reference_texts=[
                "Dies ist ein anderer Post über Business.",
                "Noch ein Text über geschäftliche Themen."
            ],
            threshold=0.7
        )

        if result.get("available"):
            logger.info(f"  Similarity: {result['avg_similarity']:.2%}")
            logger.info(f"  Passed: {result['passed']}")
            logger.success("✅ Style Validator working!")
            return True
        else:
            logger.warning("⚠️ Style Validator not available (model not loaded)")
            return False

    except Exception as e:
        logger.error(f"❌ Style Validator failed: {e}")
        return False

async def test_readability_checker():
    """Test readability checker."""
    logger.info("Testing Readability Checker...")
    try:
        from src.agents.readability_checker import ReadabilityChecker

        checker = ReadabilityChecker()

        # Test with simple text
        result = await checker.process(
            "Dies ist ein kurzer Satz. Noch ein kurzer Satz. LinkedIn Posts sollten gut lesbar sein."
        )

        if result.get("available"):
            metrics = result.get("metrics", {})
            logger.info(f"  WSTF: {metrics.get('wiener_sachtextformel', 'N/A')}")
            logger.info(f"  Flesch: {metrics.get('flesch_reading_ease', 'N/A')}")
            logger.info(f"  Avg Sentence Length: {metrics.get('avg_sentence_length', 'N/A'):.1f}")
            logger.success("✅ Readability Checker working!")
            return True
        else:
            logger.warning("⚠️ Readability Checker not available")
            return False

    except Exception as e:
        logger.error(f"❌ Readability Checker failed: {e}")
        return False

async def test_ngram_extraction():
    """Test N-gram extraction."""
    logger.info("Testing N-gram Extraction...")
    try:
        from src.agents.profile_analyzer import ProfileAnalyzerAgent

        analyzer = ProfileAnalyzerAgent()

        # Test with sample posts
        posts = [
            "Ich bin absolut überzeugt dass dies funktioniert.",
            "Meine Erfahrung zeigt dass wir das schaffen.",
            "Ich bin fest davon überzeugt dass es klappt."
        ]

        result = analyzer._extract_ngram_patterns(posts)

        if result.get("available"):
            logger.info(f"  Bigrams found: {len(result['typical_bigrams'])}")
            logger.info(f"  Trigrams found: {len(result['typical_trigrams'])}")
            logger.info(f"  Signatures found: {len(result['signature_combinations'])}")

            if result['typical_bigrams']:
                logger.info(f"  Sample bigrams: {result['typical_bigrams'][:3]}")

            logger.success("✅ N-gram Extraction working!")
            return True
        else:
            logger.error("❌ N-gram Extraction not available")
            return False

    except Exception as e:
        logger.error(f"❌ N-gram Extraction failed: {e}")
        import traceback
        traceback.print_exc()
        return False

async def main():
    """Run all tests."""
    logger.info("🧪 Testing Optimization Features\n")

    results = {
        "Grammar Checker": await test_grammar_checker(),
        "Style Validator": await test_style_validator(),
        "Readability Checker": await test_readability_checker(),
        "N-gram Extraction": await test_ngram_extraction()
    }

    logger.info("\n" + "="*50)
    logger.info("📊 Test Results:")
    logger.info("="*50)

    for name, passed in results.items():
        status = "✅ PASS" if passed else "❌ FAIL"
        logger.info(f"  {name}: {status}")

    all_passed = all(results.values())

    if all_passed:
        logger.success("\n🎉 All tests passed!")
    else:
        logger.warning("\n⚠️ Some tests failed - check the logs above")

    return all_passed

if __name__ == "__main__":
    success = asyncio.run(main())
    exit(0 if success else 1)
