from pathlib import Path


def create_protein_ligand_complex(
    protein_pdbqt_filepath, docking_pose_pdbqt_filepath, ligand_id, output_filepath
):
    """
    Create a protein-ligand complex PDB file out of separate protein and ligand files.

    Parameters
    ----------
    protein_pdbqt_filepath : str or pathlib.Path
        Filepath of the PDB file containing the protein.
    docking_pose_pdbqt_filepath : str or pathlib.Path
        Filepath of the PDB file containing the ligand.
    ligand_id : str
        An identifier for the ligand to write into the PDB file.
    output_filepath : str or pathlib.Path
        Output filepath of the PDB file containing the protein-ligand complex.

    Returns
    -------
    pathlib.Path
        Complete filepath of the created protein-ligand complex PDB file.
    """

    def pdbqt_to_pdbblock(pdbqt_filepath):
        lines = []
        with open(Path(pdbqt_filepath).with_suffix(".pdbqt")) as file:
            for line in file:
                # we are only interested in lines starting with "ATOM"
                # and ignore the rest.
                if line[:4] == "ATOM":
                    lines.append(line[:67].strip())
        return "\n".join(lines)

    protein_pdbblock = pdbqt_to_pdbblock(protein_pdbqt_filepath)

    ligand_pdbblock = pdbqt_to_pdbblock(docking_pose_pdbqt_filepath)

    full_output_filepath = Path(output_filepath).with_suffix(".pdb")
    with open(full_output_filepath, "w") as file:
        file.write(protein_pdbblock)
        file.write(f"\nCOMPND    {ligand_id}\n")
        file.write(ligand_pdbblock)

    return full_output_filepath