from __future__ import annotations

import argparse
import json

from govoplan_core.core.module_management import module_install_plan_commands, saved_module_install_plan
from govoplan_core.db.session import configure_database, get_database
from govoplan_core.settings import settings


def main() -> None:
    parser = argparse.ArgumentParser(description="Print the GovOPlaN module package install plan.")
    parser.add_argument("--database-url", default=settings.database_url, help="Database URL containing system_settings.")
    parser.add_argument("--format", choices=("shell", "json"), default="shell", help="Output format.")
    args = parser.parse_args()

    configure_database(str(args.database_url))
    with get_database().session() as session:
        plan = saved_module_install_plan(session)

    if args.format == "json":
        print(json.dumps({
            "updated_at": plan.updated_at,
            "items": [item.as_dict() for item in plan.items],
            "commands": list(module_install_plan_commands(plan)),
        }, indent=2, sort_keys=True))
        return

    if not plan.items:
        print("# No planned module package changes.")
        return

    print("# GovOPlaN module package install plan")
    if plan.updated_at:
        print(f"# Updated: {plan.updated_at}")
    for command in module_install_plan_commands(plan):
        print(command)


if __name__ == "__main__":
    main()
