#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
import sys
from datetime import date
from pathlib import Path

SERVER_DIR = Path(__file__).resolve().parents[1]
SRC_DIR = SERVER_DIR / "src"
if str(SRC_DIR) not in sys.path:
    sys.path.insert(0, str(SRC_DIR))

from app.core.agent_enums import AgentRunSource  # noqa: E402
from app.db.session import get_session_factory  # noqa: E402
from app.services.digital_employee_finance_report_task import (  # noqa: E402
    DigitalEmployeeFinanceReportTaskService,
)


def main() -> None:
    parser = argparse.ArgumentParser(description="Generate finance report PDF by digital employee.")
    parser.add_argument("--type", choices=["weekly", "quarterly", "annual"], default="weekly")
    parser.add_argument("--start-date", type=_parse_date, default=None)
    parser.add_argument("--end-date", type=_parse_date, default=None)
    parser.add_argument("--recipient", action="append", default=[])
    parser.add_argument("--send-email", action="store_true")
    parser.add_argument("--dry-run-email", action="store_true")
    args = parser.parse_args()

    session_factory = get_session_factory()
    with session_factory() as db:
        result = DigitalEmployeeFinanceReportTaskService(db).generate_report(
            report_type=args.type,
            start_date=args.start_date,
            end_date=args.end_date,
            recipients=args.recipient or None,
            send_email=args.send_email or args.dry_run_email,
            dry_run_email=args.dry_run_email,
            source=AgentRunSource.USER_MESSAGE.value,
        )
        db.commit()
        print(json.dumps(result, ensure_ascii=False, indent=2))


def _parse_date(value: str) -> date:
    return date.fromisoformat(value)


if __name__ == "__main__":
    main()
