"""
FSAL Service Runner - The Iron Vault Entry Point

Usage:
  Environment variables:
    FSAL_HOST (default: 127.0.0.1)
    FSAL_PORT (default: 4848)
    FSAL_TOKEN (optional): Bearer token for API authentication
    FSAL_ROOT (REQUIRED in production): Sandbox root directory
    APERION_ENV: Set to 'dev' or 'development' for development mode

Example:
    # Development mode (CWD fallback allowed)
    APERION_ENV=dev aperion-fsal

    # Production mode (FSAL_ROOT required)
    FSAL_ROOT=/data/sandbox FSAL_TOKEN=secret aperion-fsal

PRODUCTION MODE ENFORCEMENT:
If APERION_ENV is not 'dev' or 'development' AND FSAL_ROOT is not set,
the service will REFUSE to start. This prevents accidental exposure
of the host filesystem.
"""

from __future__ import annotations

import logging
import os
import sys
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from fastapi import FastAPI

# Configure logging early
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
    stream=sys.stderr,
)
log = logging.getLogger("aperion-fsal")


def _is_production_mode() -> bool:
    """Check if we're in production mode."""
    env_mode = os.environ.get("APERION_ENV", "").lower()
    return env_mode not in ("dev", "development", "test", "testing")


def _validate_production_config() -> bool:
    """
    Validate configuration for production mode.

    Returns:
        True if configuration is valid, False otherwise.
    """
    errors: list[str] = []

    # FSAL_ROOT is REQUIRED in production
    fsal_root = os.environ.get("FSAL_ROOT")
    if not fsal_root:
        errors.append("FSAL_ROOT environment variable is required in production mode")
        errors.append("  Set APERION_ENV=dev to allow CWD fallback during development")

    # FSAL_TOKEN is STRONGLY recommended in production
    fsal_token = os.environ.get("FSAL_TOKEN")
    if not fsal_token:
        log.warning(
            "FSAL_TOKEN not set - running in NO-AUTH mode. This is INSECURE for production!"
        )

    if errors:
        for error in errors:
            log.error(error)
        return False

    return True


def _print_startup_banner(host: str, port: int) -> None:
    """Print startup information."""
    env_mode = os.environ.get("APERION_ENV", "production").upper()
    fsal_root = os.environ.get("FSAL_ROOT", "<CWD fallback>")
    has_token = bool(os.environ.get("FSAL_TOKEN"))

    print(file=sys.stderr)
    print("=" * 60, file=sys.stderr)
    print("  THE IRON VAULT - Aperion FSAL v1.0.0", file=sys.stderr)
    print("=" * 60, file=sys.stderr)
    print(f"  Mode:     {env_mode}", file=sys.stderr)
    print(f"  Sandbox:  {fsal_root}", file=sys.stderr)
    print(f"  Auth:     {'ENABLED' if has_token else 'DISABLED (insecure!)'}", file=sys.stderr)
    print(f"  Binding:  http://{host}:{port}", file=sys.stderr)
    print("=" * 60, file=sys.stderr)
    print(file=sys.stderr)


def main() -> int:
    """
    Main entry point for The Iron Vault FSAL service.

    Returns:
        Exit code (0 for success, 1 for failure).
    """
    # Production mode validation
    if _is_production_mode():
        if not _validate_production_config():
            return 1
    else:
        log.info("Running in DEVELOPMENT mode - some safety checks relaxed")

        # In dev mode, set APERION_ENV if not set (for sandbox fallback)
        if not os.environ.get("APERION_ENV"):
            os.environ["APERION_ENV"] = "dev"

    # Log security warnings
    if not os.environ.get("FSAL_TOKEN"):
        log.warning(
            "FSAL_TOKEN not set - running in NO-AUTH mode. "
            "This is insecure and should only be used for development!"
        )

    host = os.environ.get("FSAL_HOST", "127.0.0.1")
    port = int(os.environ.get("FSAL_PORT", "4848"))

    _print_startup_banner(host, port)

    try:
        import uvicorn

        uvicorn.run(
            "aperion_fsal.service.app:app",
            host=host,
            port=port,
            reload=False,
            log_level="info",
        )
        return 0
    except ImportError as e:
        log.error("Missing dependency: %s", e)
        log.error("Install with: pip install uvicorn[standard]")
        return 1
    except Exception as e:
        log.exception("Failed to start The Iron Vault: %s", e)
        return 1


def create_app() -> FastAPI:
    """Factory that returns the Iron Vault FastAPI application instance.

    Used by the legacy FSAL runner adapter and E2E test harness.
    """
    from .service.app import app  # noqa: F811

    return app


if __name__ == "__main__":
    raise SystemExit(main())
