import sys
import traceback
from pathlib import Path

from watchfiles import watch

from ssb_pubmd.core import render_article
from ssb_pubmd.core.project import create_project


def run_cli(system_arguments: list[str]) -> None:
    match system_arguments:
        case [_, "create", article_title]:
            _create_project(article_title)
        case [_, "render", file_path]:
            _render(file_path)
        case [_, "preview", file_path]:
            _preview(file_path)
        case _:
            print("Usage:")
            print("  ssb-pubmd create ARTICLE_TITLE")
            print("  ssb-pubmd render FILE_NAME")
            print("  ssb-pubmd preview FILE_NAME")
            sys.exit(1)


def _create_project(article_name: str) -> None:
    """Creates a project folder with a template file.

    The folder and file name is set to a sanitized version of the given article name.
    """
    name = create_project(article_name)
    print(f"Created project folder {name}.")
    print(f"Created template file {name}/{name}.qmd")
    print("Open the template file for further instructions.")


def _preview(file_path: str) -> None:
    _render(file_path)

    print("Watching for file changes...")
    try:
        for _changes in watch(file_path):
            print("Found changes.")
            _sync_updated_file(file_path)
            print("Watching for file changes...")
    except KeyboardInterrupt:
        print("Stopping...")


def _render(file_path: str) -> None:
    if Path(file_path).suffix != ".qmd":
        print("Only Quarto Markdown (.qmd) files are supported.")
        sys.exit(1)

    _sync_updated_file(file_path)


def _sync_updated_file(file_path: str) -> None:
    print("Syncing updated document...")
    try:
        preview_url = render_article(file_path)
        print(f"Content synced successfully. Preview URL: {preview_url}")
    except Exception:
        print("Failed to sync content. Full error log:")
        traceback.print_exc()
