import os
import requests
from snownlp import SnowNLP
import smtplib
from email.message import EmailMessage
from datetime import datetime

# Configuration
NEWS_API_KEY = os.getenv('NEWS_API_KEY')  # Get from https://newsapi.org
EMAIL_ADDRESS = os.getenv('EMAIL_ADDRESS')
EMAIL_PASSWORD = os.getenv('EMAIL_PASSWORD')
SEARCH_TERMS = "新能源 OR IPO OR 电动汽车 IPO OR 中国汽车"

# def fetch_news():
#     """Fetch Chinese news articles about new energy/car IPOs"""
#     url = 'https://newsapi.org/v2/everything'
#     params = {
#         'q': SEARCH_TERMS,
#         'language': 'zh',
#         'sortBy': 'publishedAt',
#         'apiKey': NEWS_API_KEY,
#         'pageSize': 20
#     }
#     print(f"NEWS_API_KEY: {NEWS_API_KEY}")
#     response = requests.get(url, params=params)
#     response.raise_for_status()
#     return response.json().get('articles', [])


def fetch_news():
    """Fetch top headlines about new energy/car IPOs in China and Hong Kong"""
    url = 'https://newsapi.org/v2/top-headlines'
    params = {
        'q': SEARCH_TERMS,
        'language': 'zh',
        'apiKey': NEWS_API_KEY,
        'pageSize': 20,
        'country': 'cn',  # Country code for China
        # 'country': 'hk',  # Uncomment this line to switch to Hong Kong
    }
    print(f"NEWS_API_KEY: {NEWS_API_KEY}")
    response = requests.get(url, params=params)
    response.raise_for_status()
    
    print(f"Complete URL for testing: {response.request.url}")
    print(f"Request Params: {params}")
    print(f"Response Status Code: {response.status_code}")
    print(f"Response Content: {response.text}")
    return response.json().get('articles', [])

def analyze_articles(articles):
    """Analyze sentiment and filter relevant news"""
    processed = []
    
    for article in articles:
        content = f"{article['title']}. {article['description']}"
        sentiment = SnowNLP(content).sentiments
        
        # Filter criteria (adjust as needed)
        if any(keyword in content for keyword in ["IPO", "上市", "申购"]) and sentiment >= 0.4:
            processed.append({
                'title': article['title'],
                'url': article['url'],
                'source': article['source']['name'],
                'date': article['publishedAt'],
                'sentiment': round(sentiment, 2)
            })
    
    return processed

def send_notification(articles, debug_mode=True):
    """Send alerts to console (debug) or email (production)"""
    if not articles:
        return

    if debug_mode:
        # Console output version
        print(f"\n=== IPO Alerts ({datetime.now().strftime('%Y-%m-%d %H:%M')}) ===")
        for idx, article in enumerate(articles, 1):
            print(f"{idx}. {article['title']}")
            print(f"   Source: {article['source']}")
            print(f"   Sentiment: {article['sentiment']}")
            print(f"   URL: {article['url']}")
            print(f"   Date: {article['date']}\n{'-'*50}")
    else:
        # Original email version (kept for reference)
        msg = EmailMessage()
        msg['Subject'] = f"新能源IPO警报 - {datetime.now().strftime('%Y-%m-%d %H:%M')}"
        msg['From'] = EMAIL_ADDRESS
        msg['To'] = EMAIL_ADDRESS
        
        email_body = "发现重要IPO相关新闻:\n\n"    
        for idx, article in enumerate(articles, 1):
            email_body += f"""【{idx}】{article['title']}
- 来源: {article['source']}
- 情绪值: {article['sentiment']}
- 链接: {article['url']}
- 时间: {article['date']}
\n"""
        
        msg.set_content(email_body)
        
        with smtplib.SMTP('smtp.gmail.com', 587) as server:
            server.starttls()
            server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
            server.send_message(msg)

def main():
    # Step 1: Fetch news
    articles = fetch_news()
    
    # Step 2: Analyze content
    filtered_articles = analyze_articles(articles)
    
    # Step 3: Send notification (debug mode to console)
    if filtered_articles:
        send_notification(filtered_articles, debug_mode=True)
        print(f"Found {len(filtered_articles)} relevant articles")
    else:
        print("No significant updates found")

if __name__ == "__main__":
    main()        