"Fast API module for the recommender system"

# import sys
# sys.path.append(
#     r"."
# )


import asyncio
import json
import logging
from datetime import datetime

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field

from services.company_profile.company_profile import CompanyProfileMaker
from services.company_profile.data_classes.company_info import CompanyInfo
from services.company_profile.data_classes.llm_results import LLMResults
# from the parent directory
from utils import url_parser
from utils.dynamo_db import DynamoDB

# from fastapi.responses import JSONResponse




company_profile = APIRouter(
    prefix="/company_profile",
    tags=["company_profile"],
    responses={404: {"description": "Not found"}},
    dependencies=[],  # add dependencies here
)


# get company url from the url path and acq_direction from the query parameter
@company_profile.get("/", status_code=200)
async def check_company(url: str):
    "Get recommendations for a company"
    company_url_parsed = url_parser.parsed_url(url)

    dynamo_db = DynamoDB()
    # check if the company is in the dynamodb
    response = dynamo_db.get_item(dynamo_db.company_list_table, company_url_parsed.url)

    if response is None or response["scrapped"] is False:
        dynamo_db.create_or_update_company_list(
            company_url_parsed.url,
            scrapped=False,
        )

        logging.warning("%s not in database", company_url_parsed.url)
        return HTTPException(status_code=500, detail="Company not in database")

    return {"message": "Company in database", "status_code": 200}


class CompanyProfileRequest(BaseModel):
    url: str
    company_stock_ticker: str = None
    is_pe_shop: bool = False


@company_profile.post("/make_profile/")
async def make_profile(company_profile_request: CompanyProfileRequest):
    "Get recommendations for a company"

    try:
        company_profile_maker = CompanyProfileMaker(
            company_url=company_profile_request.url,
            stock_ticker=company_profile_request.company_stock_ticker,
            is_pe_shop=company_profile_request.is_pe_shop,
        )
        await company_profile_maker.main()
        return {
            "status_code": 200,
            "message": "Company profile for {} created".format(
                company_profile_request.url
            ),
        }

    except Exception as e:
        logging.error(e, exc_info=True)
        {
            "status_code": 500,
            "message": f"Error creating company profile for {company_profile_request.url}: {str(e)}",
        }


@company_profile.get("/website/")
async def get_profile(url: str):
    "Get recommendations for a company"
    company_url_parsed = url_parser.parsed_url(url)

    dynamo_db = DynamoDB()
    # check if the company is in the dynamodb
    response = dynamo_db.get_item(dynamo_db.company_info_table, company_url_parsed.url)

    if response is None:
        logging.warning("%s not in company info table", company_url_parsed.url)
        return {"message": "Not in database"}

    company_info = CompanyInfo(**response)

    if company_info.logo is None:
        # get the brand from the url
        ci = CompanyProfileMaker(company_url_parsed.url)
        company_info = await ci.load_brand(supplied_company_info=company_info)

    # replace with the front expected format
    return json.loads(company_info.model_dump_json())


@company_profile.get("/LLM/")
async def get_llm(url: str):
    "Get recommendations for a company"
    company_url_parsed = url_parser.parsed_url(url)

    dynamo_db = DynamoDB()
    # check if the company is in the dynamodb
    response = dynamo_db.get_item(dynamo_db.llm_table, company_url_parsed.url)

    if response is None:
        logging.warning("%s not in LLM table", company_url_parsed.url)
        return {"message": "Not in database"}

    llm_results = LLMResults(**response)

    new_response = llm_results.model_dump()
    new_llm_results = {}
    # only for the time being, we need to filter the results
    for llm_result in sorted(new_response["LLM_results"], key=lambda x: x["Order"]):
        if llm_result["header"] == "Mangaement":
            continue

        if llm_result["header"] in new_llm_results:
            new_llm_results[llm_result["header"]]["response"] += (
                "\n" + llm_result["response"]
            )

        else:
            new_llm_results[llm_result["header"]] = llm_result

    llm_results.LLM_results = list(new_llm_results.values())

    # replace with the front expected format
    return json.loads(llm_results.model_dump_json())


@company_profile.get("/leadership/")
async def get_leadership(url: str):
    "Get recommendations for a company"
    company_url_parsed = url_parser.parsed_url(url)

    dynamo_db = DynamoDB()
    # check if the company is in the dynamodb
    response = dynamo_db.get_item(dynamo_db.llm_table, company_url_parsed.url)

    if response is None:
        logging.warning("%s not in LLM table", company_url_parsed.url)
        return {"message": "Not in database"}

    if "leadership" in response:
        if response["leadership"] == "":
            response["leadership"] = None

    llm_results_db = LLMResults(**response)
    if llm_results_db.leadership is None:

        company_profile_maker = CompanyProfileMaker(company_url_parsed.url)
        company_profile_maker.llm_results = llm_results_db.model_dump()["LLM_results"]
        leadership = await company_profile_maker.map_leadership()
        llm_results_db.leadership = llm_results_db.create_leadership(leadership)

        # update the company info in the dynamodb
        llm_results_db.update_modify()
        dynamo_db.upload_to_dynamodb(dynamo_db.llm_table, llm_results_db.model_dump())

    if llm_results_db.leadership is None:
        return []

    # replace with the front expected format
    return json.loads(
        json.dumps(llm_results_db.model_dump()["leadership"]["leadership"])
    )


if __name__ == "__main__":
    # import uvicorn
    # uvicorn.run(company_profile)
    asyncio.run(get_leadership("https://www.neweracap.com"))
