import re
from bs4 import BeautifulSoup

EXCERPT_KEYWORDS = [
    "acquisition", "acquire", "acquiring",
    "merge", "purchase", "buy",
    "subsidiary", "subsidiaries",
]

EXHIBIT_SKIP_PATTERNS = re.compile(
    r'^(exhibit21|exhibit\s|list of\s|subsidiaries|\d+$|\*)', re.IGNORECASE
)

def extract_acquisition_excerpts(html_content):
    if not html_content:
        return []
    soup = BeautifulSoup(html_content, "html.parser")
    excerpts = []
    for div in soup.find_all("div"):
        spans = div.find_all("span", recursive=False)
        if not spans:
            continue
        text = " ".join(span.get_text(strip=True) for span in spans).strip()
        if len(text) < 50:
            continue
        text_lower = text.lower()
        if any(keyword in text_lower for keyword in EXCERPT_KEYWORDS):
            excerpts.append(text)
    return excerpts

def extract_attached_documents(submission_text):
    documents = []
    blocks = re.split(r'<DOCUMENT>', submission_text, flags=re.IGNORECASE)

    def extract_tag(block, tag):
        match = re.search(rf'<{tag}>([^\n\r<]+)', block, flags=re.IGNORECASE)
        return match.group(1).strip() if match else None

    for block in blocks[1:]:
        doc = {
            "type": extract_tag(block, "TYPE"),
            "sequence": extract_tag(block, "SEQUENCE"),
            "filename": extract_tag(block, "FILENAME"),
            "description": extract_tag(block, "DESCRIPTION"),
        }
        if doc["type"] and doc["filename"]:
            documents.append(doc)
    return documents

def extract_subsidiaries(document):
    soup = BeautifulSoup(document, "html.parser")
    tables = soup.find_all("table")
    if tables:
        return _extract_from_tables(tables)
    return _extract_from_divs(soup)

def _extract_from_tables(tables):
    subsidiaries = []
    for table in tables:
        first_non_empty_row_skipped = False
        for tr in table.find_all("tr"):
            for cell in tr.find_all("td"):
                text = cell.get_text(separator=" ", strip=True).replace("\xa0", "")
                if not text:
                    continue
                if not first_non_empty_row_skipped:
                    first_non_empty_row_skipped = True
                    break
                subsidiaries.append(text)
                break
    return subsidiaries

def _extract_from_divs(soup):
    subsidiaries = []
    for div in soup.find_all("div", recursive=True):
        if div.find("div"):
            continue
        text = div.get_text(separator=" ", strip=True).replace("\xa0", "")
        if not text or len(text) < 3:
            continue
        if EXHIBIT_SKIP_PATTERNS.match(text):
            continue
        subsidiaries.append(text)
    return subsidiaries
