import toml


def convert_version(version):
    version = version.strip('^~=')
    return version


def convert_pyproject_to_setup():
    with open('pyproject.toml', 'r') as f:
        pyproject = toml.load(f)

    poetry_config = pyproject['tool']['poetry']
    dependencies = poetry_config.get('dependencies', {})
    dev_dependencies = poetry_config.get('dev-dependencies', {})

    install_requires = []
    for package, version in dependencies.items():
        if package != 'python':
            install_requires.append(f'{package}{convert_version(version)}')

    extras_require = {
        'dev': [f'{pkg}{convert_version(ver)}' for pkg, ver in dev_dependencies.items()]
    } if dev_dependencies else {}

    setup_kwargs = {
        'name': poetry_config['name'],
        'version': poetry_config['version'],
        'description': poetry_config.get('description', ''),
        'author': ', '.join(poetry_config.get('authors', [])),
        'install_requires': install_requires,
        'extras_require': extras_require,
    }

    with open('setup.py', 'w') as f:
        f.write(f"""
from setuptools import setup

setup(
    name='{setup_kwargs['name']}',
    version='{setup_kwargs['version']}',
    description='{setup_kwargs['description']}',
    author='{setup_kwargs['author']}',
    install_requires={install_requires},
    extras_require={extras_require},
)
""")


def convert_pyproject_to_requirements():
    with open('pyproject.toml', 'r') as f:
        pyproject = toml.load(f)

    poetry_config = pyproject['tool']['poetry']
    dependencies = poetry_config.get('dependencies', {})
    dev_dependencies = poetry_config.get('dev-dependencies', {})

    with open('requirements.txt', 'w') as f:
        for package, version in dependencies.items():
            if package != 'python':
                f.write(f'{package}{convert_version(version)}\n')

        if dev_dependencies:
            f.write('\n# Development dependencies\n')
            for package, version in dev_dependencies.items():
                f.write(f'{package}{convert_version(version)}\n')


if __name__ == '__main__':
    convert_pyproject_to_setup()
    convert_pyproject_to_requirements()
