export_pdf.py 2.21 KB
from __future__ import annotations

import argparse
import json
import sys
from datetime import datetime
from pathlib import Path
from typing import Optional

PROJECT_ROOT = Path(__file__).resolve().parents[2]
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

from services.engines.report.renderers.pdf_renderer import PDFRenderer
from utils.runtime_paths import FINAL_REPORTS_DIR, ensure_runtime_dirs


def resolve_input_path(raw_path: Optional[str]) -> Optional[Path]:
    if raw_path:
        path = Path(raw_path).expanduser()
        if not path.is_absolute():
            path = PROJECT_ROOT / path
        return path

    ensure_runtime_dirs()
    ir_dir = FINAL_REPORTS_DIR / "ir"
    if not ir_dir.exists():
        return None

    candidates = sorted(ir_dir.glob("*.json"), key=lambda item: item.stat().st_mtime, reverse=True)
    return candidates[0] if candidates else None


def export_pdf(ir_file_path: Path) -> Path:
    with ir_file_path.open("r", encoding="utf-8") as file:
        document_ir = json.load(file)

    renderer = PDFRenderer()
    pdf_bytes = renderer.render_to_bytes(document_ir, optimize_layout=True)

    topic = document_ir.get("metadata", {}).get("topic", "report")
    output_dir = FINAL_REPORTS_DIR / "pdf"
    output_dir.mkdir(parents=True, exist_ok=True)

    filename = f"report_{topic}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
    output_path = output_dir / filename
    output_path.write_bytes(pdf_bytes)
    return output_path


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="Export a report IR JSON file to PDF.")
    parser.add_argument(
        "input",
        nargs="?",
        help="Path to a report IR JSON file. Defaults to the newest file under var/reports/final/ir.",
    )
    return parser


def main(argv: Optional[list[str]] = None) -> int:
    parser = build_parser()
    args = parser.parse_args(argv)

    input_path = resolve_input_path(args.input)
    if input_path is None or not input_path.exists():
        parser.error("Could not find a report IR JSON file to export.")

    output_path = export_pdf(input_path)
    print(output_path)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())