#!/usr/bin/env python3

# Copyright SUSE LLC
# SPDX-License-Identifier: GPL-2.0-or-later

# ruff: file-ignore[print]

"""Helper tool to initialize the openQA developer test environment with fixtures."""

import argparse
import os
import subprocess  # ruff: ignore[suspicious-subprocess-import]
import sys
from pathlib import Path

try:
    from argparse import BooleanOptionalAction
except ImportError:  # pragma: no cover
    BooleanOptionalAction = None


def init(*, fixtures: str = "*.pl", reset: bool = True, silent: bool = False) -> None:
    """Initialize or reset the openQA test database with standard fixtures and mock assets."""
    # Ensure t/fixtures exists
    fixtures_dir = Path("t/fixtures")
    if not fixtures_dir.exists():
        print(f"Error: Fixtures directory {fixtures_dir} not found.", file=sys.stderr)
        sys.exit(1)

    schema_name = os.environ.get("OPENQA_DATABASE_SEARCH_PATH", "public")

    if not silent:
        if reset:
            print(f"Resetting schema '{schema_name}'...")
        print(f"Deploying schema and loading fixtures from '{fixtures}'...")

    # We use a Perl script invoked via subprocess.
    # This ensures compatibility with openQA's DBIC schema, connections, and fixture files.
    env = os.environ.copy()
    env["FIXTURES_GLOB"] = fixtures
    env["RESET_SCHEMA"] = "1" if reset else "0"

    try:
        # Run Perl with the standalone backend script
        subprocess.run(
            ["/usr/bin/perl", "t/lib/init-test-fixtures.pl"],
            env=env,
            check=True,
            capture_output=silent,
            text=True,
        )
    except subprocess.CalledProcessError as e:
        print("Error: Failed to initialize test fixtures.", file=sys.stderr)
        if e.stderr:
            print(e.stderr, file=sys.stderr)
        sys.exit(e.returncode)

    if not silent:
        print("\n========================================================================")
        print("  openQA interactive test environment has been initialized")
        print("========================================================================\n")
        print(f"  Database resets and schema deployed onto '{schema_name}'.")
        print(f"  Loaded fixtures matching: {fixtures}")
        print("  Mock assets activated.\n")
        print("  You can interact with the local Web UI using the following links:")
        print("    - Home/Overview:  http://localhost:9526/")
        print("    - Test Results:   http://localhost:9526/tests/overview")
        print("    - Sample Details:  http://localhost:9526/tests/99981")
        print("    - Admin Workers:  http://localhost:9526/admin/workers\n")
        print("  Authentication Info:")
        print("    - Click 'Login' in the top-right corner to log in automatically")
        print("      as the 'Demo' user (who has administrator/operator rights).\n")
        print("========================================================================\n")


def main() -> None:
    """Parse command-line arguments and run fixture initialization."""
    parser = argparse.ArgumentParser(description="Initialize the openQA developer test environment with fixtures.")
    parser.add_argument(
        "--fixtures",
        "-f",
        default="*.pl",
        help="Specify fixture files to load (default: '*.pl')",
    )
    if BooleanOptionalAction:
        parser.add_argument(
            "--reset",
            action=BooleanOptionalAction,
            default=True,
            help="Drop and recreate the schema before populating (default: True)",
        )
    else:
        parser.add_argument(
            "--reset",
            dest="reset",
            action="store_true",
            default=True,
            help="Drop and recreate the schema before populating (default: True)",
        )
        parser.add_argument(
            "--no-reset",
            dest="reset",
            action="store_false",
            help="Do not drop and recreate the schema before populating",
        )
    parser.add_argument(
        "--silent",
        "-s",
        action="store_true",
        default=False,
        help="Suppress summary and status output",
    )
    args = parser.parse_args()
    init(fixtures=args.fixtures, reset=args.reset, silent=args.silent)


if __name__ == "__main__":
    main()
