"""CLI commands for cost savings reports.

Provides ``robot-resources report weekly`` and ``robot-resources report monthly``
with optional ``--format json`` for machine-readable output.
"""

from __future__ import annotations

import sys

import click

from robot_resources.tracking.db import OutcomeDB
from robot_resources.tracking.reports import (
    build_report,
    format_report_json,
    format_report_table,
)


def _get_report_db() -> OutcomeDB:
    """Create and connect an OutcomeDB for report queries.

    Uses the default path (``~/.robot-resources/outcomes.db``).
    Temporarily redirects stdout → stderr during connect() to prevent
    structlog info messages from polluting CLI data output.
    Monkeypatched in tests to return a test DB.
    """
    db = OutcomeDB()
    _stdout = sys.stdout
    sys.stdout = sys.stderr
    try:
        db.connect()
    finally:
        sys.stdout = _stdout
    return db


@click.group()
def report() -> None:
    """View cost savings reports."""
    pass


@report.command()
@click.option(
    "--format",
    "fmt",
    type=click.Choice(["table", "json"]),
    default="table",
    help="Output format (default: table).",
)
def weekly(fmt: str) -> None:
    """Show cost savings report for the last 7 days."""
    db = _get_report_db()
    try:
        data = build_report(db, period="weekly")
        if fmt == "json":
            click.echo(format_report_json(data))
        else:
            click.echo(format_report_table(data))
    finally:
        db.close()


@report.command()
@click.option(
    "--format",
    "fmt",
    type=click.Choice(["table", "json"]),
    default="table",
    help="Output format (default: table).",
)
def monthly(fmt: str) -> None:
    """Show cost savings report for the last 30 days."""
    db = _get_report_db()
    try:
        data = build_report(db, period="monthly")
        if fmt == "json":
            click.echo(format_report_json(data))
        else:
            click.echo(format_report_table(data))
    finally:
        db.close()
