#!/usr/bin/env python3
"""Production runner for Chronara backend - handles installed app paths."""

import os
import sys
from pathlib import Path

# In production, the app structure will be:
# C:\Program Files\Chronara\
#   ├── Chronara.exe
#   ├── resources/
#   │   ├── models/
#   │   └── src/
#   │       └── backend/

# Find the app installation directory
if getattr(sys, 'frozen', False):
    # Running in PyInstaller bundle
    app_dir = Path(sys.executable).parent
else:
    # Running as script - check if we're in an installed app
    current_file = Path(__file__).resolve()

    # Check if we're in a typical Windows install location
    if "Program Files" in str(current_file) or "AppData" in str(current_file):
        # We're installed - go up to find resources
        app_dir = current_file.parent.parent.parent.parent
    else:
        # Development mode
        app_dir = current_file.parent.parent.parent

# Set up paths
resources_dir = app_dir / "resources"
if resources_dir.exists():
    models_dir = resources_dir / "models"
    src_dir = resources_dir / "src"
else:
    # Fallback to development structure
    models_dir = app_dir / "models"
    src_dir = app_dir / "src"

# Add src to path so imports work
sys.path.insert(0, str(src_dir))

# Set environment variable for models
os.environ['CHRONARA_MODELS_DIR'] = str(models_dir)

# Now import and run the app
from backend.main import app
import uvicorn

if __name__ == "__main__":
    print(f"Starting Chronara backend...")
    print(f"App directory: {app_dir}")
    print(f"Models directory: {models_dir}")
    print(f"Source directory: {src_dir}")

    # Run the app
    uvicorn.run(
        app,
        host="127.0.0.1",
        port=8000,
        log_level="info"
    )