# Convert Cedar Backup's Poetry v2 pyproject.toml to a version compatible with
# Poetry v1, which is all that is available in Debian as of this writing.
#
# This is a quick-and-dirty hack.  It's not intended to be general-purpose.
# For instance, it ignores all of the development-related configuration, which
# isn't needed for the Debian build.

import sys
from datetime import datetime
from tomlkit import comment, document, nl, table, parse, dumps, inline_table

original = parse(sys.stdin.read())

migrated = document()
migrated.add(comment("Version of Cedar Backup's pyproject.toml compatible with Poetry v1"))
migrated.add(comment(f"This document was generated at {datetime.today().isoformat()}"))

build_system = table()
build_system["requires"] = [ "poetry-core" ]
build_system["build-backend"] = "poetry.core.masonry.api"
migrated.add("build-system", build_system)

tool = table()
poetry = table()
scripts = table()
dependencies = table()
extras = table()
poetry.add("scripts", scripts)
poetry.add("dependencies", dependencies)
poetry.add("extras", extras)
tool.add("poetry", poetry)
migrated.add("tool", tool)

poetry["name"] = original["project"]["name"]
poetry["version"] = original["project"]["version"]
poetry["description"] = original["project"]["description"]
poetry["keywords"] = original["project"]["keywords"]
poetry["authors"] = [ f"{a['name']} <{a['email']}>" for a in original["project"]["authors"] ]
poetry["license"] = original["project"]["license"]
poetry["readme"] = original["project"]["readme"]
poetry["homepage"] = original["project"]["urls"]["homepage"]
poetry["repository"] = original["project"]["urls"]["repository"]
poetry["include"] = original["tool"]["poetry"]["include"]
poetry["packages"] = original["tool"]["poetry"]["packages"]
poetry["classifiers"] = original["tool"]["poetry"]["classifiers"]
poetry["scripts"] = original["tool"]["poetry"]["scripts"]

poetry["dependencies"]["python"] = original["project"]["requires-python"]

poetry["dependencies"].update({
   d.split(" ", 1)[0]: d.split(" ", 1)[1].strip("()")
   for d in original["project"]["dependencies"]
})

inline = inline_table()
inline.update({
   d.split(" ", 1)[0]: { "version": d.split(" ", 1)[1].strip("()"), "optional": True }
   for d in original["project"]["optional-dependencies"]["docs"]
})
poetry["dependencies"].update(inline)

poetry["extras"]["docs"] = [
   d.split(" ", 1)[0]
   for d in original["project"]["optional-dependencies"]["docs"]
]

print(dumps(migrated))
