#!/usr/bin/env python3
"""
FLHIP Scraper v3 - Component Tests
Run individual tests to verify setup

Usage:
    python test_components.py api      # Test Claude API connection
    python test_components.py db       # Test database connection
    python test_components.py rss      # Test RSS feed fetch
    python test_components.py scrape   # Test article scraping
    python test_components.py full     # Test full pipeline with sample article
"""

import sys
import json


def test_api():
    """Test Claude API connection."""
    print("Testing Claude API connection...")
    
    from config import ANTHROPIC_API_KEY
    if not ANTHROPIC_API_KEY:
        print("ANTHROPIC_API_KEY not set")
        return False
    
    try:
        import anthropic
        client = anthropic.Anthropic(api_key=ANTHROPIC_API_KEY)
        
        response = client.messages.create(
            model="claude-sonnet-4-20250514",
            max_tokens=100,
            messages=[{"role": "user", "content": "Say 'API working' and nothing else."}]
        )
        
        result = response.content[0].text
        print(f"Claude API working: {result}")
        return True
        
    except Exception as e:
        print(f"API error: {e}")
        return False


def test_db():
    """Test database connection."""
    print("Testing database connection to restaurant_leads_usa2...")
    
    try:
        from db_handler import get_connection, get_lead_count, TABLE_NAME
        
        conn = get_connection()
        if conn:
            cursor = conn.cursor()
            cursor.execute(f"DESCRIBE {TABLE_NAME}")
            columns = cursor.fetchall()
            cursor.close()
            conn.close()
            print(f"Connected successfully")
            print(f"Table {TABLE_NAME} has {len(columns)} columns")
            print(f"Current leads: {get_lead_count()}")
            return True
        else:
            print("Database connection failed")
            return False
            
    except Exception as e:
        print(f"Database error: {e}")
        return False


def test_rss():
    """Test RSS feed fetching."""
    print("Testing RSS feed fetch...")
    
    try:
        from rss_fetcher import fetch_all_feeds
        
        articles = fetch_all_feeds()
        print(f"Fetched {len(articles)} articles from feeds")
        
        if articles:
            print("\nSample articles:")
            for a in articles[:3]:
                print(f"  - {a['title'][:60]}...")
        
        return len(articles) > 0
        
    except Exception as e:
        print(f"RSS error: {e}")
        return False


def test_scrape():
    """Test article scraping."""
    print("Testing article scraping...")
    
    try:
        from rss_fetcher import scrape_article_content
        
        # Test with a known good URL
        test_url = "https://whatnow.com/atlanta/restaurants/"
        content = scrape_article_content(test_url)
        
        if content and len(content) > 100:
            print(f"Scraped {len(content)} characters")
            print(f"Preview: {content[:200]}...")
            return True
        else:
            print("No content scraped")
            return False
            
    except Exception as e:
        print(f"Scrape error: {e}")
        return False


def test_full():
    """Test full pipeline with a sample article."""
    print("Testing full pipeline with sample article...")
    
    try:
        from claude_processor import process_article
        
        # Sample article that SHOULD pass
        test_title = "New Mexican Restaurant Coming to Downtown Memphis in 2026"
        test_content = """
        MEMPHIS, TN - Chef Maria Rodriguez is bringing authentic Mexican cuisine 
        to downtown Memphis with the opening of Casa Rodriguez. The restaurant, 
        located at 456 Beale Street, is set to open in March 2026.
        
        The 3,500 square foot space will feature traditional recipes from 
        Oaxaca, including handmade tortillas and mole sauces. Rodriguez, who 
        trained in Mexico City, has been planning this restaurant for years.
        
        "Memphis is ready for real Mexican food," said Rodriguez. 
        
        The restaurant is currently hiring and can be reached at 901-555-0456.
        Contact: maria@casarodriguez.com
        """
        test_url = "https://example.com/memphis-restaurant-news"
        test_date = "2025-12-28"
        
        print("\nProcessing test article...")
        result = process_article(test_title, test_content, test_url, test_date)
        
        if result:
            print("Lead extracted successfully!")
            print(json.dumps(result, indent=2))
            return True
        else:
            print("No lead extracted (check Claude prompt)")
            return False
            
    except Exception as e:
        print(f"Pipeline error: {e}")
        import traceback
        traceback.print_exc()
        return False


def main():
    if len(sys.argv) < 2:
        print(__doc__)
        sys.exit(1)
    
    test = sys.argv[1].lower()
    
    tests = {
        "api": test_api,
        "db": test_db,
        "rss": test_rss,
        "scrape": test_scrape,
        "full": test_full,
    }
    
    if test == "all":
        results = {}
        for name, func in tests.items():
            print(f"\n{'='*50}")
            results[name] = func()
        
        print(f"\n{'='*50}")
        print("SUMMARY")
        print("="*50)
        for name, passed in results.items():
            status = "PASS" if passed else "FAIL"
            print(f"  {name}: {status}")
    
    elif test in tests:
        success = tests[test]()
        sys.exit(0 if success else 1)
    
    else:
        print(f"Unknown test: {test}")
        print("Available: api, db, rss, scrape, full, all")
        sys.exit(1)


if __name__ == "__main__":
    main()
