"""
init-mater-project

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

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

import subprocess
import sys
from pathlib import Path

import click
from loguru import logger


@logger.catch
def serve_app(config):
    """Serve MATER app for visualization"""
    app_path = Path(config.paths.app_path)

    if not app_path.exists():
        click.echo(f"❌ MATER app not found. Expected location: {app_path}")
        return

    click.echo("🚀 Launching MATER app...")
    click.echo("   App will open in your browser")
    click.echo("   Press Ctrl+C to stop\n")

    try:
        subprocess.run(
            [
                sys.executable,
                "-m",
                "streamlit",
                "run",
                str(app_path),
                "--",
                "--output-folder",
                str(config.paths.output_folder),
            ]
        )
    except KeyboardInterrupt:
        click.echo("\n\n👋 App stopped")
        raise
    except subprocess.CalledProcessError as e:
        click.echo(f"❌ Error launching app: {e}")
        raise
    except Exception as e:
        click.echo(f"❌ Unexpected error: {e}")
        raise
