from __future__ import annotations

import argparse
import json
from pathlib import Path

from .parser import StatementParseError, parse_directory, parse_statement


def main() -> int:
    parser = argparse.ArgumentParser(description="Parse bank statements by header signature.")
    parser.add_argument("path", type=Path, help="Statement file or directory")
    args = parser.parse_args()

    try:
        batches = (
            parse_directory(args.path)
            if args.path.is_dir()
            else parse_statement(args.path)
        )
    except (OSError, StatementParseError) as exc:
        parser.error(str(exc))

    summaries = [
        {
            "file": batch.source_file.name,
            "sheet": batch.sheet_name,
            "bank": batch.bank_name,
            "template": batch.template_id,
            "header_row": batch.header_row,
            "period_start": batch.period_start.isoformat() if batch.period_start else None,
            "period_end": batch.period_end.isoformat() if batch.period_end else None,
            "transactions": len(batch.transactions),
            "warnings": list(batch.warnings),
        }
        for batch in batches
    ]
    print(json.dumps(summaries, ensure_ascii=False, indent=2))
    return 0


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