"""
init-mater-project

Copyright (C) 2025 [Lauranne Sarribouette] <lauranne.sarribouette@univ-grenoble-alpes.fr>

SPDX-License-Identifier: LGPL-3.0-or-later
"""

import subprocess
from pathlib import Path

from click.testing import CliRunner

from src.init_mater_project.main import main


def test_project_generation_creates_proper_structure(tmp_path):
    """Test that project generation creates all necessary directories and files"""
    runner = CliRunner()

    with runner.isolated_filesystem(temp_dir=tmp_path):
        # Generate new MATER project in current directory
        result = runner.invoke(main, [])
        assert result.exit_code == 0
        assert "initialized!" in result.output

        project_dir = Path(".")

        # Verify essential files exist
        assert (project_dir / "config.toml").exists()
        assert (project_dir / "README.md").exists()

        # Verify directory structure
        assert (project_dir / "data" / "raw").is_dir()
        assert (project_dir / "data" / "input").is_dir()
        assert (project_dir / "data" / "references").is_dir()
        assert (project_dir / "data" / "dimensions").is_dir()
        assert (project_dir / "transforms" / "datasets").is_dir()
        assert (project_dir / "transforms" / "dimensions").is_dir()
        assert (project_dir / "outputs").is_dir()
        assert (project_dir / "src").is_dir()
        assert (project_dir / "examples").is_dir()

        # Verify config.toml has valid content
        config_content = (project_dir / "config.toml").read_text(encoding="utf-8")
        assert "[simulation]" in config_content
        assert "[paths]" in config_content
        assert "[provider]" in config_content
        assert "[metadata]" in config_content


def test_data_generate_workflow(tmp_path):
    """Test data pipeline"""
    runner = CliRunner()

    with runner.isolated_filesystem(temp_dir=tmp_path):
        # Step 1: Generate new MATER project
        result_init = runner.invoke(main, ["test-notebook-project"])
        assert result_init.exit_code == 0
        assert (
            "MATER project 'test-notebook-project' initialized!" in result_init.output
        )

        project_dir = Path("test-notebook-project").resolve()

        # Verify project structure was created
        assert project_dir.exists()
        assert (project_dir / "config.toml").exists()
        assert (project_dir / "data" / "raw").exists()

        # Setup: copy minimal example CSV from generated project examples to raw
        src_csv = project_dir / "examples" / "minimal_raw_example.csv"
        dst_csv = project_dir / "data" / "raw" / "minimal_raw_example.csv"
        dst_csv.write_text(src_csv.read_text(encoding="utf-8"), encoding="utf-8")

        # Step 2: Generate transformation notebook using subprocess
        result_generate = subprocess.run(
            ["uv", "run", "mater-cli", "data", "generate"],
            cwd=project_dir,
            capture_output=True,
            text=True,
        )
        assert result_generate.returncode == 0
        assert "Generated" in result_generate.stdout

        # Verify notebook was created
        notebook_path = (
            project_dir / "transforms" / "datasets" / "minimal_raw_example.ipynb"
        )
        assert notebook_path.exists()
        assert notebook_path.suffix == ".ipynb"


def test_data_pipeline_with_example_workflow(tmp_path):
    """Test data pipeline using --example flag"""
    runner = CliRunner()

    with runner.isolated_filesystem(temp_dir=tmp_path):
        # Step 1: Generate new MATER project
        result_init = runner.invoke(main, ["example-project"])
        assert result_init.exit_code == 0

        project_dir = Path("example-project").resolve()

        # Step 2: Test data generate with example data using subprocess
        result_generate = subprocess.run(
            ["uv", "run", "mater-cli", "data", "generate", "--example"],
            cwd=project_dir,
            capture_output=True,
            text=True,
            encoding="utf-8",
        )
        assert result_generate.returncode == 0
        assert "Example data" in result_generate.stdout

        # Verify notebook was created
        notebook_path = project_dir / "examples" / "minimal_raw_example.ipynb"
        assert notebook_path.exists()
        assert notebook_path.suffix == ".ipynb"


def test_data_generate_in_empty_raw_directory(tmp_path):
    """Test data generate when raw directory is empty"""
    runner = CliRunner()

    with runner.isolated_filesystem(temp_dir=tmp_path):
        # Step 1: Generate new MATER project
        result_init = runner.invoke(main, ["empty-raw-test"])
        assert result_init.exit_code == 0

        project_dir = Path("empty-raw-test").resolve()

        # Step 2: Try to generate scripts with empty raw directory using subprocess
        result = subprocess.run(
            ["uv", "run", "mater-cli", "data", "generate"],
            cwd=project_dir,
            capture_output=True,
            text=True,
            encoding="utf-8",
        )
        assert result.returncode == 0
        assert "No supported dataset files found" in result.stdout
