import argparse
import sys
import csv
from typing import List
from my_pubmed_package.pubmed_module import (
    search_pubmed_ids,
    fetch_pubmed_details_bulk,
    parse_and_filter_papers
)


def main() -> None:
    """
    The CLI entry point. 
    Usage examples:
      poetry run get-papers-list "heart attack therapy" -d -f results.csv
    """
    parser = argparse.ArgumentParser(
        description="Fetch PubMed papers for a query. Filter those with pharma/biotech affiliations."
    )
    parser.add_argument("query", help="PubMed query (quotes if multi-word).")
    parser.add_argument("-d", "--debug", action="store_true", help="Print debug information.")
    parser.add_argument("-f", "--file", help="Filename to save CSV. If not provided, prints to console.")
    args = parser.parse_args()

    query: str = args.query
    debug: bool = args.debug
    filename = args.file

    # 1) Search PMIDs
    pmids: List[str] = search_pubmed_ids(query, retmax=50, verbose=debug)
    if not pmids:
        print("[INFO] No PMIDs found.")
        sys.exit(0)

    # 2) EFetch details in bulk
    articles = fetch_pubmed_details_bulk(pmids, verbose=debug)
    if not articles:
        print("[INFO] No article details retrieved.")
        sys.exit(0)

    # 3) Parse & filter to only those with pharma/biotech affiliations
    final_rows = parse_and_filter_papers(articles, verbose=debug)
    if not final_rows:
        print("No papers found with pharma/biotech-affiliated authors.")
        sys.exit(0)

    # 4) Output
    if filename:
        # Write CSV
        fieldnames = [
            "PubmedID", 
            "Title", 
            "Publication Date", 
            "Non-academic Author(s)", 
            "Company Affiliation(s)",
            "Corresponding Author Email"
        ]
        try:
            with open(filename, mode="w", newline="", encoding="utf-8") as f:
                writer = csv.DictWriter(f, fieldnames=fieldnames)
                writer.writeheader()
                for row in final_rows:
                    writer.writerow(row)
            print(f"Results saved to {filename}")
        except OSError as e:
            print(f"[ERROR] Could not write to file '{filename}': {e}")
    else:
        # Print to console
        print("\n--- Pharma/Biotech Papers ---\n")
        for row in final_rows:
            print(f"PubmedID: {row['PubmedID']}")
            print(f"Title: {row['Title']}")
            print(f"Publication Date: {row['Publication Date']}")
            print(f"Non-academic Author(s): {row['Non-academic Author(s)']}")
            print(f"Company Affiliation(s): {row['Company Affiliation(s)']}")
            print(f"Corresponding Author Email: {row['Corresponding Author Email']}")
            print("------------------------------------------")


if __name__ == "__main__":
    main()


'''import os
import argparse
import sys
import csv
from typing import List, Dict, Optional

try:
    import pandas as pd
except ImportError:
    pd = None

import openai

from get_papers_list.pubmed import (
    fetch_pubmed_ids,
    fetch_pubmed_details_bulk,
)

# If you want to keep the old naive classification:
def naive_classification(authors: List[Dict[str, Dict]], verbose=False):
    """
    Example fallback: naive classification based on keywords.
    Returns (company_authors, non_academic_authors, company_affiliations)
    """
    company_keywords = ["pharma", "pharmaceutical", "biotech", "inc", "ltd", "gmbh", "corp", "co.", "company"]
    academic_keywords = ["university", "univ.", "college", "school", "institute", "academia", "hospital"]

    company_authors = []
    non_academic = []
    company_affils = set()

    for a in authors:
        name = a["name"]
        affs = a["affiliations"] if a["affiliations"] else []
        if not affs:
            # no affiliation => call them non-academic
            non_academic.append(name)
            continue
        has_academic = False
        for aff in affs:
            aff_lower = aff.lower()
            if any(k in aff_lower for k in academic_keywords):
                has_academic = True
            if any(k in aff_lower for k in company_keywords):
                company_authors.append((name, aff))
                company_affils.add(aff)
        if not has_academic:
            non_academic.append(name)

    return company_authors, non_academic, list(company_affils)


# Import the new Llama-based helpers
from get_papers_list.pubmed import (
    llama_classify_authors,
    llama_summarize_paper,
    llama_rank_papers_by_relevance
)


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Fetch PubMed papers for a given query and filter those with pharma/biotech authors."
    )
    parser.add_argument("query", help="PubMed query (use quotes for multi-word queries)")
    parser.add_argument("-d", "--debug", action="store_true", help="Print debug information")
    parser.add_argument(
        "-f", 
        "--file", 
        metavar="FILENAME",
        help="Specify filename to save results (CSV or XLSX). If omitted, outputs to console."
    )
    parser.add_argument(
        "--use-llama",
        action="store_true",
        help="Use the Llama model to classify authors, summarize papers, and rank by relevance."
    )

    args = parser.parse_args()

    query: str = args.query
    debug: bool = args.debug
    filename: Optional[str] = args.file
    use_llama: bool = args.use_llama

    # Initialize Llama client if requested
    client: Optional[openai.OpenAI] = None
    if use_llama:
        if debug:
            print("[DEBUG] Initializing Llama client (SambaNova).")
        try:
            client = openai.OpenAI(
                api_key=os.environ.get("SAMBANOVA_API_KEY"),
                base_url="https://api.sambanova.ai/v1",
            )
        except Exception as e:
            print("[ERROR] Could not initialize Llama client:", e)
            client = None  # fallback to None

    if debug and use_llama:
        print("[DEBUG] Using Llama for classification, summarization, ranking...")

    # 1) Fetch PMIDs
    pmids: List[str] = fetch_pubmed_ids(query, retmax=50, verbose=debug)
    print(f"Found {len(pmids)} PubMed IDs for query: '{query}'")
    if not pmids:
        print("[INFO] No PMIDs found. Exiting.")
        return

    # 2) Bulk fetch details
    details_dict = fetch_pubmed_details_bulk(pmids, verbose=debug)

    # 3) Build an output list
    results_for_output: List[Dict[str, str]] = []

    # We'll store intermediate data for ranking if using Llama
    papers_data_for_ranking = []

    for pmid in pmids:
        paper = details_dict.get(pmid)
        if not paper:
            continue

        # If Llama is available, we do advanced classification
        authors = paper["authors"]
        if use_llama and client:
            classification_map = llama_classify_authors(client, authors, verbose=debug)
            # We'll parse classification_map to identify if any author is "Pharma/Biotech"
            # also track "non-academic" authors
            company_authors = []
            non_academic = []
            company_affils = set()

            for a in authors:
                name = a["name"]
                c = classification_map.get(name, "Other").lower()
                if "pharma" in c or "biotech" in c:
                    # We'll call that "company"
                    # If the user wants, we can store aff. But we only have name->classification
                    # If we want the actual affiliation text, we can do more advanced prompts
                    company_authors.append((name, "; ".join(a["affiliations"])))
                    for aff in a["affiliations"]:
                        company_affils.add(aff)
                elif "academic" not in c:
                    # If it's not academic, we treat it as non-academic
                    non_academic.append(name)

        else:
            # fallback naive classification
            company_authors, non_academic, affs = naive_classification(authors, verbose=debug)
            company_affils = set(affs)

        # If we have at least 1 pharma/biotech author, keep this paper
        if company_authors:
            # Summarize if Llama is on
            summary_text = ""
            if use_llama and client:
                summary_text = llama_summarize_paper(
                    client,
                    paper["title"],
                    paper["abstract"],
                    verbose=debug
                )

            row = {
                "PubmedID": paper["pmid"],
                "Title": paper["title"],
                "Publication Date": paper["pub_date"],
                "Non-academic Author(s)": "; ".join(set(non_academic)),
                "Company Affiliation(s)": "; ".join(company_affils),
                "Corresponding Author Email": paper["corresponding_email"],
            }
            # Also store summary for ranking
            row["summary"] = summary_text
            results_for_output.append(row)

    if not results_for_output:
        print("No papers found with authors affiliated to pharmaceutical/biotech companies.")
        return

    # 4) If using Llama, rank papers by relevance
    if use_llama and client:
        results_for_output = llama_rank_papers_by_relevance(
            client,
            query,
            results_for_output,
            verbose=debug
        )

    # 5) Save or print
    if filename:
        file_lower = filename.lower()
        if file_lower.endswith(".xlsx"):
            # Save as Excel
            if pd is None:
                print("[ERROR] pandas not installed. Cannot save to Excel.")
                return
            df = pd.DataFrame(results_for_output)
            # you might want to drop the "summary" column if you don't want in final output
            try:
                df.to_excel(filename, index=False)
                print(f"Results saved to Excel file: {filename}")
            except Exception as e:
                print(f"[ERROR] Could not write Excel file '{filename}': {e}")
        else:
            # CSV
            try:
                fieldnames = [
                    "PubmedID",
                    "Title",
                    "Publication Date",
                    "Non-academic Author(s)",
                    "Company Affiliation(s)",
                    "Corresponding Author Email",
                    "summary"  # if you want to keep the Llama summary
                ]
                with open(filename, mode="w", newline="", encoding="utf-8") as csv_file:
                    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
                    writer.writeheader()
                    for row in results_for_output:
                        writer.writerow(row)
                print(f"Results saved to CSV file: {filename}")
            except OSError as e:
                print(f"[ERROR] Could not write CSV file '{filename}': {e}")
    else:
        # Print to console
        print("\nResults (Pharma/Biotech papers):\n")
        for row in results_for_output:
            print(f"PubmedID: {row['PubmedID']}")
            print(f"Title: {row['Title']}")
            print(f"Publication Date: {row['Publication Date']}")
            print(f"Non-academic Author(s): {row['Non-academic Author(s)']}")
            print(f"Company Affiliation(s): {row['Company Affiliation(s)']}")
            print(f"Corresponding Author Email: {row['Corresponding Author Email']}")
            if use_llama:
                print(f"Summary: {row['summary']}")
            print("-------------------------------------------")
'''