"""CLI entry point for flat-fhir."""

from __future__ import annotations

import json
import sys

import click


@click.group()
@click.version_option(version="0.1.0")
def main():
    """flat-fhir: Convert FHIR JSON bundles into flat, LLM-friendly XLSX spreadsheets."""
    pass


@main.command()
@click.argument("input_file", type=click.Path(exists=True))
@click.option("-o", "--output", default="output.xlsx", help="Output XLSX file path.")
@click.option("--sheets", default=None, help="Comma-separated list of sheets to include.")
def convert(input_file: str, output: str, sheets: str | None):
    """Convert a FHIR Bundle JSON to XLSX."""
    from flat_fhir.core import flatten

    sheet_list = sheets.split(",") if sheets else None
    ff = flatten(input_file, output=output, sheets=sheet_list)
    active_sheets = ff.sheets()
    click.echo(f"Wrote {output} with sheets: {', '.join(active_sheets)}")


@main.command()
@click.argument("url")
@click.option("-o", "--output", default="output.xlsx", help="Output XLSX file path.")
@click.option("--sheets", default=None, help="Comma-separated list of sheets to include.")
@click.option("--auth", default=None, help="Bearer token for FHIR server auth.")
def fetch(url: str, output: str, sheets: str | None, auth: str | None):
    """Fetch a FHIR resource from a server and convert to XLSX."""
    import requests
    from flat_fhir.core import flatten

    headers = {"Accept": "application/fhir+json"}
    if auth:
        headers["Authorization"] = f"Bearer {auth}"

    # If URL points to a Patient, fetch everything via $everything
    if "/Patient/" in url and not url.endswith("$everything"):
        everything_url = url.rstrip("/") + "/$everything"
        click.echo(f"Fetching {everything_url} ...")
        resp = requests.get(everything_url, headers=headers)
    else:
        click.echo(f"Fetching {url} ...")
        resp = requests.get(url, headers=headers)

    resp.raise_for_status()
    bundle = resp.json()

    sheet_list = sheets.split(",") if sheets else None
    ff = flatten(bundle, output=output, sheets=sheet_list)
    active_sheets = ff.sheets()
    click.echo(f"Wrote {output} with sheets: {', '.join(active_sheets)}")


@main.command()
@click.argument("input_files", nargs=-1, type=click.Path(exists=True))
@click.option("-o", "--output", default="merged.xlsx", help="Output XLSX file path.")
def merge(input_files: tuple[str, ...], output: str):
    """Merge multiple FHIR Bundle JSON files into a single XLSX."""
    from flat_fhir.core import merge as do_merge

    if len(input_files) < 2:
        click.echo("Error: provide at least 2 input files.", err=True)
        sys.exit(1)

    ff = do_merge(list(input_files), output=output)
    click.echo(f"Merged {len(input_files)} bundles → {output} with sheets: {', '.join(ff.sheets())}")


@main.command()
@click.argument("input_file", type=click.Path(exists=True))
@click.option("-o", "--output", default="bundle.json", help="Output FHIR Bundle JSON file path.")
def unflatten(input_file: str, output: str):
    """Convert an XLSX file back to a FHIR Bundle JSON."""
    from flat_fhir.core import unflatten as do_unflatten

    bundle = do_unflatten(input_file, output=output)
    n = len(bundle.get("entry", []))
    click.echo(f"Wrote {output} with {n} resources.")


if __name__ == "__main__":
    main()
