"""
finverse.export.report — generate a one-pager summary report.
"""
from __future__ import annotations

from pathlib import Path


def to_report(model_or_results, path: str = "finverse_report.txt", fmt: str = "txt") -> str:
    """
    Export a DCF model to a plain text one-pager summary.

    Parameters
    ----------
    model_or_results : DCF or DCFResults
    path             : output path
    fmt              : "txt" (default) — pdf support requires reportlab

    Returns
    -------
    str — path to saved file

    Example
    -------
    >>> from finverse.export import to_report
    >>> to_report(model, "apple_summary.txt")
    """
    from finverse.utils.display import console
    from finverse.models.dcf import DCF

    if isinstance(model_or_results, DCF):
        if model_or_results._results is None:
            model_or_results.run()
        results = model_or_results._results
        data = model_or_results._data
    else:
        results = model_or_results
        data = None

    a = results.assumptions
    name = data.name if data and hasattr(data, "name") else "Company"
    ticker = data.ticker if data and hasattr(data, "ticker") else ""

    lines = [
        "=" * 60,
        f"  {name} ({ticker}) — DCF Summary",
        "=" * 60,
        "",
        "ASSUMPTIONS",
        f"  WACC:                  {a.wacc:.1%}",
        f"  Terminal growth:       {a.terminal_growth:.1%}",
        f"  EBITDA margin:         {a.ebitda_margin:.1%}",
        f"  Tax rate:              {a.tax_rate:.1%}",
        f"  Projection years:      {a.projection_years}",
        "",
        "PROJECTIONS",
    ]

    for _, row in results.fcf_projections.iterrows():
        lines.append(
            f"  {int(row['year'])}:  Revenue ${row['revenue']:.1f}B  |  "
            f"EBITDA ${row['ebitda']:.1f}B  |  FCF ${row['fcf']:.1f}B  |  "
            f"PV ${row['pv_fcf']:.1f}B"
        )

    lines += [
        "",
        "VALUATION",
        f"  PV of FCFs:            ${results.pv_fcfs:.1f}B",
        f"  Terminal value (PV):   ${results.pv_terminal:.1f}B",
        f"  Enterprise value:      ${results.enterprise_value:.1f}B",
        f"  Net debt:              ${results.net_debt:.1f}B",
        f"  Equity value:          ${results.equity_value:.1f}B",
        f"  Implied share price:   ${results.implied_price:.2f}",
    ]

    if results.current_price:
        lines.append(f"  Current price:         ${results.current_price:.2f}")
        if results.upside_pct is not None:
            direction = "Upside" if results.upside_pct >= 0 else "Downside"
            lines.append(f"  {direction}:               {abs(results.upside_pct):.1%}")

    lines += ["", "Generated by finverse — github.com/finverse", "=" * 60]

    content = "\n".join(lines)
    path = str(Path(path).with_suffix(".txt"))
    with open(path, "w") as f:
        f.write(content)

    console.print(f"[green]✓[/green] Report saved to [bold]{path}[/bold]")
    return path
