from bs4 import BeautifulSoup
import re
import html


def __getCompanyMetadata(parsed: BeautifulSoup) -> dict:
    """Function to extract company Standard Industrial Classification (SIC)
    code, SIC type (i.e. description), company location, state of incorporation,
    and the end of its fiscal year.
    Searches the raw HTML of the company identification section of the page
    using regular expressions.
    
    Arguments:
        parsed {BeautifulSoup} -- Parsed HTML from company EDGAR filing.
    
    Returns:
        dict -- Company metadata with keys `sic`, `sic_type`, `location`,
                `incorporation_state`, and `fiscal_year_end`.
    """

    # Company metadata container
    metadata_container = parsed.find('p', class_='identInfo')
    # String representation of HTML (used in RegEx)
    metadata_str = str(metadata_container)

    # Dictionary for company metadata
    company_metadata = dict()

    # RegEx for extracting SIC and SIC type
    sic_re = re.compile(r'SIC.+?:.+?(\d+?)<\/a> -(.+?)<br')
    # Getting SIC and SIC type match
    sic_matches = sic_re.findall(metadata_str)
    # Saving SIC and stripped, HTML-parsed SIC type
    company_metadata['sic'] = sic_matches[0][0]
    company_metadata['sic_type'] = html.unescape(sic_matches[0][1]).strip()

    # RegEx for extracting company location (state)
    location_re = re.compile(r'State location:.+?>(\w+?)<\/a>')
    # Getting company location
    location_matches = location_re.findall(metadata_str)
    # Saving company location
    company_metadata['location'] = location_matches[0].strip()

    # RegEx for extracting state of incorporation
    incorp_state_re = re.compile(r'State of Inc\.:.+?>(\w+?)<\/strong>')
    # Getting state of incorporation
    incorp_match = incorp_state_re.findall(metadata_str)[0]
    # Saving state of incorporation
    company_metadata['incorporation_state'] = incorp_match.strip()

    # RegEx for extracting end of fiscal year
    fiscal_year_re = re.compile(r'Fiscal Year End:.+?(\d{4})')
    # Getting end of fiscal year
    fiscal_year_match = fiscal_year_re.findall(metadata_str)[0]
    # Saving end of fiscal year (in mm-dd format)
    fy_formatted = fiscal_year_match[0:2] + '-' + fiscal_year_match[2:]
    company_metadata['fiscal_year_end'] = fy_formatted

    return company_metadata