"stock performance endpoints"

from fastapi import APIRouter, HTTPException

from services.stock_info.stock_performance import StockPerformance
from utils.url_parser import parsed_url

stock_info = APIRouter(
    prefix="/stock_info",
    tags=["stock_info"],
    responses={
        404: {"description": "Not found"},
        500: {"description": "Internal Server Error"},
    },
    dependencies=[],
)


@stock_info.post("/stock_performance/")
async def get_stock_performance(
    company_url: str = None,
    ticker: str = None,
    rebase: bool = False,
    duration: int = 5,
):
    """
    Get stock price information of a company
    Company url: str: The company url
    Ticker: str: The ticker of the stock
    Rebase: bool: Rebase the stock prices (default: False)
    Duration: int: The duration of the stock data (default: 5 years)
    """

    stp = StockPerformance()
    try:
        if not ticker and not company_url:
            return HTTPException(
                status_code=400,
                detail="Ticker or company url is required to fetch stock data",
            )

        if ticker is not None:
            stock_data = stp.get_stock_info(
                ticker=ticker, duration=duration, rebase=rebase
            )

        elif company_url is not None:
            company_url = parsed_url(company_url).url
            stock_data = stp.get_stock_info(
                company_url=company_url, duration=duration, rebase=rebase
            )
        return stock_data

    except ValueError as e:
        return HTTPException(
            status_code=404,
            detail=f"Ticker or company url is required to fetch stock data: {e}",
        )
