from typing import Dict

from fastapi import FastAPI, HTTPException

from model_server.ilastik import IlastikPixelClassifierModel, IlastikObjectClassifierModel
from model_server.model import DummyImageToImageModel
from model_server.session import Session
from model_server.workflow import infer_image_to_image

app = FastAPI(debug=True)
session = Session()

@app.on_event("startup")
def startup():
    pass

@app.get('/')
def read_root():
    return {'success': True}

@app.get('/models')
def list_active_models():
    return session.describe_loaded_models()

@app.put('/models/dummy/load/')
def load_dummy_model() -> dict:
    return {'model_id': session.load_model(DummyImageToImageModel)}

@app.put('/models/ilastik/pixel_classification/load/')
def load_ilastik_pixel_classification_model(project_file: str) -> dict:
    return {
        'model_id': session.load_model(
            IlastikPixelClassifierModel,
            {'project_file': project_file}
        )
    }

@app.put('/models/ilastik/object_classification/load/')
def load_ilastik_object_classification_model(project_file: str) -> dict:
    return {
        'model_id': session.load_model(
            IlastikObjectClassifierModel,
            {'project_file': project_file}
        )
    }

@app.put('/infer/from_image_file')
def infer_img(model_id: str, input_filename: str, channel: int = None) -> dict:
    if model_id not in session.describe_loaded_models().keys():
        raise HTTPException(
            status_code=409,
            detail=f'Model {model_id} has not been loaded'
        )
    inpath = session.inbound.path / input_filename
    if not inpath.exists():
        raise HTTPException(
            status_code=404,
            detail=f'Could not find file:\n{inpath}'
        )
    record = infer_image_to_image(
        inpath,
        session.models[model_id]['object'],
        session.outbound.path,
        channel=channel,
    )
    session.record_workflow_run(record)
    return record