#!/usr/bin/env python3
"""
Start Jupyter Lab with a preloaded Odoo environment.

Expects the directory to already be initialized via init-odoo-jupyter.
"""

from __future__ import annotations

import argparse
import os
import secrets
import subprocess
from pathlib import Path


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Start Jupyter Lab with Odoo kernel bootstrap."
    )
    parser.add_argument("path", help="Directory previously initialized by init-odoo-jupyter")
    parser.add_argument(
        "database",
        nargs="?",
        default=os.environ.get("DB_NAME", "odoo"),
    )
    parser.add_argument(
        "token",
        nargs="?",
        default=None,
    )
    args = parser.parse_args()

    notebook_dir = Path(args.path).resolve()
    ipython_dir = notebook_dir / ".ipython"
    config_dir = notebook_dir / ".jupyter"
    
    if not (notebook_dir / "main.ipynb").exists():
        print(f"Error: {notebook_dir} does not look initialized.")
        print("Run 'task init-odoo-jupyter <path>' first.")
        raise SystemExit(1)

    token = args.token or secrets.token_hex(16)

    env = os.environ.copy()
    env["DB_NAME"] = args.database
    env.setdefault("PGHOST", "localhost")
    env.setdefault("PGPORT", "5432")
    env.setdefault("PGUSER", "odoo")
    env.setdefault("PGPASSWORD", "odoo")
    env["IPYTHONDIR"] = str(ipython_dir)
    env["JUPYTER_CONFIG_DIR"] = str(config_dir)

    print()
    print("Starting Jupyter Lab with Odoo")
    print(f"Database : {args.database}")
    print(f"Notebook : {notebook_dir}")
    print()

    cmd = [
        "jupyter-lab",
        f"--ServerApp.root_dir={notebook_dir}",
        f"--ServerApp.token={token}",
        # "--ServerApp.open_browser=False",
        "--ServerApp.port=8888",
    ]

    subprocess.run(cmd, env=env)

    # log_path = notebook_dir / "jupyter.log"

    # with open(log_path, "w") as log:
    #     process = subprocess.Popen(
    #         cmd,
    #         env=env,
    #         # start_new_session=True,
    #         stdout=log,
    #         stderr=log,
    #     )

    # print(f"PID : {process.pid}")
    # print(f"Log : {log_path}")


if __name__ == "__main__":
    main()