import sys
from acquiscan import extract
from acquiscan.sec_client import SECClient
from acquiscan.scan_utils import (
    EXHIBIT_FORM_TYPES,
    SUBSIDIARY_EXHIBIT_PREFIXES,
    create_result,
    filing_url,
)

def get_subsidiary_docs(sec_client, company_info, filing):
    submission_text = sec_client.get_filing_submission_text(
        company_info["cik"], filing["accessionNumberClean"], filing["accessionNumber"]
    )
    if not submission_text:
        return []
    documents = extract.extract_attached_documents(submission_text)
    return [d for d in documents if d["type"].lower().startswith(SUBSIDIARY_EXHIBIT_PREFIXES)]

def process_exhibit_doc(sec_client, company_info, filing, doc, portfolio, silent):
    if not silent:
        print(f"  Processing {doc['type']}: {doc['filename']}", file=sys.stderr)
    content = sec_client.get_filing_document(
        company_info["cik"], filing["accessionNumberClean"], doc["filename"]
    )
    if not content:
        return
    subs = extract.extract_subsidiaries(content)
    if not silent:
        print(f"  {len(subs)} subsidiaries found", file=sys.stderr)
    url = filing_url(company_info["cik"], filing)
    for name in subs:
        key = name.lower()
        existing = portfolio.get(key)
        if not existing or filing["filingDate"] > existing["filing_date"]:
            portfolio[key] = {
                "name": name,
                "form_type": filing["form"],
                "filing_date": filing["filingDate"],
                "url": url,
            }

def run_structured_exhibit_scan(company_name, config, silent=False, from_date=None, to_date=None):
    sec_client = SECClient(config.user_agent)
    if not silent:
        print(f"Searching for company: {company_name}", file=sys.stderr)
    company_info = sec_client.search_company(company_name)
    if not company_info:
        print("Company not found", file=sys.stderr)
        return create_result({"name": company_name, "cik": None}, portfolio=[])
    if not silent:
        print(f"Found: {company_info['name']} (CIK: {company_info['cik']})", file=sys.stderr)
    filings = sec_client.get_company_filings(
        company_info["cik"], EXHIBIT_FORM_TYPES, from_date, to_date
    )
    if not filings:
        print("No filings found", file=sys.stderr)
        return create_result(company_info, portfolio=[])
    if not silent:
        print(f"Found {len(filings)} filing(s)", file=sys.stderr)

    portfolio = {}
    for i, filing in enumerate(filings, 1):
        if not silent:
            print(
                f"[{i}/{len(filings)}] {filing['form']} ({filing['filingDate']})",
                file=sys.stderr,
            )
        subsidiary_docs = get_subsidiary_docs(sec_client, company_info, filing)
        if not subsidiary_docs:
            if not silent:
                print("  No subsidiary exhibits", file=sys.stderr)
            continue
        for doc in subsidiary_docs:
            process_exhibit_doc(sec_client, company_info, filing, doc, portfolio, silent)

    portfolio_list = sorted(portfolio.values(), key=lambda x: x["name"])
    if not silent:
        print(f"Found {len(portfolio_list)} companies", file=sys.stderr)
    return create_result(company_info, portfolio=portfolio_list)
