import google.generativeai as genai
import yfinance as yf
from dotenv import load_dotenv


load_dotenv()
genai.configure(api_key="gemini_api_key")

def analyze_stock(symbol):
    stock = yf.Ticker(symbol)
    hist = stock.history(period="1mo")

    if hist.empty:
        return f"No data found for symbol '{symbol}'. Please check the ticker."

    avg_price = hist['Close'].mean()
    last_price = hist['Close'].iloc[-1]
    trend = "upward 📈" if last_price > avg_price else "downward 📉"

    # LLM enhancement
    prompt = f"""
    Provide a short stock market analysis for {symbol} based on this info:
    - 1 month average closing price: {avg_price:.2f}
    - Last closing price: {last_price:.2f}
    - Trend: {trend}
    Keep it concise and professional.
    """
    model = genai.GenerativeModel("gemini-2.5-flash")
    llm_response = model.generate_content(prompt)

    return llm_response.text

def risk_assessment(symbol):
    stock = yf.Ticker(symbol)
    hist = stock.history(period="6mo")['Close']
    volatility = hist.pct_change().std() * (252 ** 0.5)
    risk_level = "High ⚠️" if volatility > 0.3 else "Moderate 🟡" if volatility > 0.15 else "Low ✅"

    # LLM enhancement
    prompt = f"""
    Explain the risk for {symbol} based on this data:
    - 6-month volatility: {volatility:.2f}
    - Risk level: {risk_level}
    Provide practical guidance for an investor in plain English.
    """
    model = genai.GenerativeModel("gemini-2.5-flash")
    llm_response = model.generate_content(prompt)

    return llm_response.text
def compare_stocks(symbol1, symbol2):
    stock1 = yf.Ticker(symbol1)
    stock2 = yf.Ticker(symbol2)

    hist1 = stock1.history(period="1mo")
    hist2 = stock2.history(period="1mo")

    if hist1.empty or hist2.empty:
        missing = []
        if hist1.empty: missing.append(symbol1)
        if hist2.empty: missing.append(symbol2)
        return f"No data found for {', '.join(missing)}. Please check the ticker(s)."

    avg1, last1 = hist1['Close'].mean(), hist1['Close'].iloc[-1]
    avg2, last2 = hist2['Close'].mean(), hist2['Close'].iloc[-1]

    perf1 = (last1 - hist1['Close'].iloc[0]) / hist1['Close'].iloc[0] * 100
    perf2 = (last2 - hist2['Close'].iloc[0]) / hist2['Close'].iloc[0] * 100

    better = symbol1 if perf1 > perf2 else symbol2

    prompt = f"""
    Compare two stocks: {symbol1} and {symbol2}.
    - {symbol1}: Avg = {avg1:.2f}, Last = {last1:.2f}, 1-month change = {perf1:.2f}%
    - {symbol2}: Avg = {avg2:.2f}, Last = {last2:.2f}, 1-month change = {perf2:.2f}%
    Suggest which stock is performing better and why.
    """
    model = genai.GenerativeModel("gemini-2.5-flash")
    llm_response = model.generate_content(prompt)

    return llm_response.text 

