import pathlib
import shutil

from pytest import raises

from odoo_openupgrade_wizard.cli.cli_options import (
    get_migration_step_from_options,
)
from odoo_openupgrade_wizard.tools.tools_odoo import run_odoo
from odoo_openupgrade_wizard.tools.tools_postgres import ensure_database

from . import (
    build_ctx_from_config_file,
    cli_runner_invoke,
    move_to_test_folder,
)


def test_cli_shell():
    move_to_test_folder()
    ctx = build_ctx_from_config_file()
    migration_step = get_migration_step_from_options(ctx, 1)

    # Ensure environment is clean
    db_name = "database_test_cli___shell"
    ensure_database(ctx, db_name, state="absent")
    dest_filestore_path = pathlib.Path(f"./filestore/filestore/{db_name}")
    shutil.rmtree(dest_filestore_path, ignore_errors=True)

    # Set the log prefix
    ctx.obj["log_prefix"] = "test_cli_shell"

    # Initialize the database
    stop_after_init = False
    run_odoo(
        ctx,
        migration_step,
        database=db_name,
        detached_container=not stop_after_init,
        stop_after_init=stop_after_init,
        init="base",
        execution_context="regular",
        publish_ports=False,
    )

    # Test that a simple script executes successfully
    result = cli_runner_invoke(
        [
            "shell",
            f"--database={db_name}",
            "--step=1",
            '--code="print("Hello, World!")"',
        ]
    )
    assert result.exit_code == 0
    assert "Hello, World!" in result.output

    # Test with a script that queries a model
    result = cli_runner_invoke(
        [
            "shell",
            f"--database={db_name}",
            "--step=1",
            "--code=\"print(env['res.partner'].search_count([]))\"",
        ]
    )
    assert result.exit_code == 0
    assert result.output.strip().isdigit()  # Should return a number

    # Test with missing database
    with raises(Exception):
        cli_runner_invoke(
            [
                "shell",
                "--database=nonexistent_database",
                "--step=1",
                '--script="print(env.user.name)"',
            ]
        )
