import io
import os
import re
from IPython.core.magic import register_cell_magic
from IPython.core.magic_arguments import argument, magic_arguments, parse_argstring

@magic_arguments()
@argument(
    "-p",
    "--prepend-content",
    help=("Prepend content to the file (Optional: defaults to '# AUTOGENERATED! DO NOT EDIT!\n\n')"),
)
@argument("filepath", type=str, help=("Filepath to write the file to (Required)"))
@register_cell_magic
def writefile_dbt(line, cell):
    "Write a file to disk and skip execution (overwrites the existing file if the file already exists)"
    args = parse_argstring(writefile_dbt, line)
    filepath = args.filepath

    if re.match(r'^(\'.*\')|(".*")$', filepath):
        # If the filepath is wrapped in quotes, remove them
        full_path = os.path.expanduser(filepath[1:-1])
    else:
        full_path = os.path.expanduser(filepath)

    if os.path.exists(full_path):
        print(f"Overwriting {full_path}")
    else:
        print(f"Writing {full_path}")

    prepend_content = args.prepend_content or f"-- AUTOGENERATED! DO NOT EDIT! File to edit: {filepath}.\n\n"
    mode = "w"

    with io.open(full_path, mode, encoding="utf-8") as f:
        # Remove the #| directive from the cell
        cell_lines = cell.splitlines(True)
        stripped_cell = ''.join([line for line in cell_lines if "#|" not in line])
        content = f"{prepend_content}{stripped_cell}"
        f.write(content)

    return
