"Classes for the LLM results"
import datetime
import socket
from decimal import Decimal
from typing import Dict, List

from pydantic import BaseModel
from pydantic import BaseModel as LangBaseModel
from pydantic import Field as LangField
from pydantic import field_validator

from utils.dynamo_db import DynamoDB
from utils.url_parser import parsed_url


class Leadership(BaseModel, extra="allow"):
    "Class to store image details"
    name: str
    title: str
    linkedin_link: str


class LangChainLeadership(LangBaseModel):
    "Class to store image details"
    name: str = LangField("Name", description="Name of the leader")
    title: str = LangField("Title", description="Title of the leader")
    linkedin_link: str = LangField(
        "Linkedin Link", description="Linkedin link of the leader"
    )


class LeadershipResults(LangBaseModel):
    "Class to store image details"
    leadership: list[LangChainLeadership] = []


class LLMQuery(BaseModel):
    "Class to store logo details"
    category: str
    header: str
    LLM_query: str
    Order: int
    response: str
    vector_db_query: str


class LLMResults(BaseModel):
    "Class to store company details"
    root_url: str

    leadership: Dict[str, List[Leadership]] | None = None
    LLM_results: List[LLMQuery]

    verified: bool | None = False
    verified_by: str | None = None
    verify_date: str | None = None

    created_by: str | None = socket.gethostname()
    created_date: str | None = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    modified_by: str | None = socket.gethostname()
    modified_date: str | None = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    @field_validator("leadership", mode="before")
    @classmethod
    def create_leadership(cls, raw_leadership: dict):
        "convert the list of images to the Images class"
        if raw_leadership is None:
            return None
        if raw_leadership == "":
            return None

        raw_leadership = raw_leadership.get("leadership", [])
        if len(raw_leadership) == 0 or raw_leadership is None:
            return None

        leadership_list = []
        for leader in raw_leadership:
            if isinstance(leader, Leadership):
                leadership_list.append(leader)
            else:
                leadership_list.append(Leadership(**leader))

        return {"leadership": leadership_list}

    @field_validator("LLM_results", mode="before")
    @classmethod
    def create_llm_result(cls, raw_LLM_query: list):
        "convert the list of llm queries to the Images class"
        if len(raw_LLM_query) == 0 or raw_LLM_query is None:
            return None

        query_list = []
        for query in raw_LLM_query:
            query_list.append(LLMQuery(**query))

        return query_list

    @field_validator("verified", mode="before")
    @classmethod
    def create_verified(cls, verified):
        "convert the list of llm queries to the Images class"
        if verified is True:
            return True
        return False

    def update_modify(self):
        "Update the modified date and modified by"
        self.modified_by = socket.gethostname()
        self.modified_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    @staticmethod
    def get_LLM_results(company_url):
        "Get the information from the db"

        company_url = parsed_url(company_url).url
        db = DynamoDB()
        company_llm_results = db.get_item(db.llm_table, company_url)

        if company_llm_results is None:
            raise ValueError(f"{company_url} not found in the database.")

        return LLMResults(**company_llm_results)


if __name__ == "__main__":

    comp_dict = {
        "leadership": {
            "leadership": [
                {
                    "name": "James M. Whitehurst",
                    "title": "Interim CEO and President",
                    "linkedin_link": "",
                },
                {
                    "name": "Nadav Ashkenazy",
                    "title": "Senior Vice President and Chief Revenue Officer Grow",
                    "linkedin_link": "",
                },
                {
                    "name": "Carol Carpenter",
                    "title": "Senior Vice President and Chief Marketing Officer",
                    "linkedin_link": "https://www.linkedin.com/in/carolwcarpenter/",
                },
                {
                    "name": "Marisa Eddy",
                    "title": "Senior Vice President and Chief People Officer",
                    "linkedin_link": "",
                },
                {
                    "name": "Giancarlo Fasolo",
                    "title": "Senior Vice President Aura",
                    "linkedin_link": "",
                },
                {
                    "name": "Anirma Gupta",
                    "title": "Senior Vice President and Chief Legal Officer",
                    "linkedin_link": "https://www.linkedin.com/in/anirmagupta/",
                },
                {
                    "name": "Jessica Lindl",
                    "title": "Vice President Social Impact",
                    "linkedin_link": "https://www.linkedin.com/in/jessica-lindl-8b73a5/",
                },
                {
                    "name": "Jules Shumaker",
                    "title": "Senior Vice President and Chief Revenue Officer Create",
                    "linkedin_link": "",
                },
                {
                    "name": "Felix Th",
                    "title": "Senior Vice President Product and Technology Grow",
                    "linkedin_link": "",
                },
                {
                    "name": "Luis Felipe Visoso",
                    "title": "Executive Vice President and Chief Financial Officer",
                    "linkedin_link": "https://www.linkedin.com/in/luis-felipe-visoso-aa841a22/",
                },
            ]
        },
        "root_url": "https://www.unity.com",
        "modified_date": "2024-02-15 12:23:09",
        "LLM_results": [
            {
                "Order": Decimal("20"),
                "header": "Products and Services",
                "LLM_query": "Provide short descriptions the products and services the company provides?",
                "category": "Products",
                "response": "- Unity Engine: Real-time 3D development engine for creating interactive experiences.\n- Unity Cloud: Ecosystem for real-time 3D experiences and services.\n- Unity Muse: AI-powered features for game and 3D development acceleration.\n- Parsec: Remote desktop solution for team collaboration.\n- SyncSketch: Collaboration tool for reviewing and annotating animations.\n- Ziva: Tools for creating high-quality characters for various media.\n- SpeedTree: Software for creating realistic vegetation in different environments.\n- Asset Store: Marketplace for game assets, tools, and plugins.\n- DevOps: Tools for agile development and high-quality game releases.\n- Multiplayer: Services for building and managing multiplayer games.\n- Engagement and Analytics: Tools for understanding player behavior and optimizing engagement.\n- Game Backend: Services for managing game data and player interactions.\n- Growth: Solutions for monetization, user acquisition, and device management.\n- Monetization: Strategies and tools for driving revenue from games.\n- User Acquisition: Services for acquiring new players for games.\n- Device Management: Tools for managing game performance across different devices.\n- Publishing: Services for launching and promoting games on various platforms.",
                "vector_db_query": "What are the products and services the company provides?",
            },
            {
                "Order": Decimal("30"),
                "header": "Management",
                "LLM_query": "Give back a list of names of the founders, executives, management or leadership team split by executive team and board members and their roles in the format of <name> : <role>. If you can't find it in the text, return 'leadership not found'.",
                "category": "Leadership",
                "response": "- James M. Whitehurst: Interim CEO and President\n- Nadav Ashkenazy: Senior Vice President and Chief Revenue Officer Grow\n- Carol Carpenter: Senior Vice President and Chief Marketing Officer\n- Marisa Eddy: Senior Vice President and Chief People Officer\n- Giancarlo Fasolo: Senior Vice President Aura\n- Anirma Gupta: Senior Vice President and Chief Legal Officer\n- Jessica Lindl: Vice President Social Impact\n- Jules Shumaker: Senior Vice President and Chief Revenue Officer Create\n- Felix Th: Senior Vice President Product and Technology Grow\n- Luis Felipe Visoso: Executive Vice President and Chief Financial Officer\n\nBoard of Directors:\n- Roelof Botha: Sequoia Capital Managing Member Chairman of the Board of Directors\n- Tomer BarZeev: Co-Founder ironSource\n- Mary Schmidt Campbell Ph.D: Spelman College President Emerita\n- Shlomo Dovrat: Viola Ventures Co-Founder and General Partner\n- Egon Durban: Silver Lake Partners Co-Chief Executive Officer Managing Partner\n- David Helgason: Transition Global Founding General Partner\n- Michelle K. Lee: AI tech executive Former Under Secretary of Commerce and Director of the U.S. Patent & Trademark Office Member of the MIT Corporation\n- David Kostman: Outbrain Co-Chief Executive Officer\n- Barry Schuler: DFJ Growth Managing Director & Partner\n- Robynne Sisco: Workday Vice Chair\n- Keisha Smith: Tory Burch Chief People Officer",
                "vector_db_query": "Names of the founders, executives, management or leadership team and their roles.",
            },
            {
                "Order": Decimal("40"),
                "header": "Customers",
                "LLM_query": "What organizations or companies are customers?",
                "category": "Customers",
                "response": "- ABB\n- Autoliv\n- BMW\n- Daimler Buses\n- Honda\n- Toyota\n- Volkswagen",
                "vector_db_query": "What organizations or companies are customers?",
            },
            {
                "Order": Decimal("15"),
                "header": "Overview",
                "LLM_query": "What are some remarkable statistics about the company and overview?",
                "category": "Overview_Stats",
                "response": "- Unity is the world's leading platform for creating and operating interactive real-time 3D content.\n- In 2022, Unity had more than 4 billion downloads per month of Made with Unity apps.\n- 70% of the top 1000 mobile games were made with Unity.\n- Unity Ads generated more than $1.1 billion in income for creators.\n- Unity supports creators in creating games and experiences across 20 platforms and billions of devices.",
                "vector_db_query": "What are some remarkable statistics about the company and overview?",
            },
            {
                "Order": Decimal("10"),
                "header": "Overview",
                "LLM_query": "Provide a 20 word overview of the company",
                "category": "Overview",
                "response": "Unity Technologies is a leading platform for creating interactive 3D content, empowering creators across industries with innovative tools and services.",
                "vector_db_query": "Give me some company facts, tell me about the company?",
            },
            {
                "Order": Decimal("19"),
                "header": "HQ and Founded",
                "LLM_query": "Return the completed the sentences: Company headquarter: <location>; Founded: <founded year>?",
                "category": "HQ_Founded",
                "response": "Company headquarters: San Francisco, California; Founded: 2004.",
                "vector_db_query": "Where is the company headquarted (HQ) and what year it was founded?",
            },
        ],
        "created_by": "Sagar-Asus",
        "created_date": "2024-02-15 12:23:09",
        "verify_date": None,
        "modified_by": "Sagar-Asus",
        "verified_by": None,
        "verified": "search",
    }

    company_info = LLMResults(**comp_dict)

    print(company_info.model_dump())
