from __future__ import annotations

import uuid

from fastapi import APIRouter, BackgroundTasks, HTTPException

from app.core.task_runner import TaskRunner
from app.models.schemas import InstallRequest, RemoveRequest, UpdateRequest
from app.storage.repository import Repository


router = APIRouter(prefix="/apps", tags=["apps"])
repository = Repository()
task_runner = TaskRunner(repository)


def _task_id(prefix: str) -> str:
    return f"task_{prefix}_{uuid.uuid4().hex[:12]}"


@router.get("/installed")
def installed_apps() -> list[dict]:
    return repository.list_installed_apps()


@router.post("/install")
def install_app(request: InstallRequest, background_tasks: BackgroundTasks) -> dict[str, str]:
    if not request.version:
        raise HTTPException(status_code=400, detail="version is required")
    task_id = _task_id("install")
    repository.create_task(task_id, "install", request.app_id, request.app_name)
    background_tasks.add_task(task_runner.run_install, task_id, request, "install")
    return {"taskId": task_id, "status": "queued"}


@router.post("/update")
def update_app(request: UpdateRequest, background_tasks: BackgroundTasks) -> dict[str, str]:
    if not request.version:
        raise HTTPException(status_code=400, detail="version or targetVersion is required")
    task_id = _task_id("update")
    repository.create_task(task_id, "update", request.app_id, request.app_name)
    background_tasks.add_task(task_runner.run_install, task_id, request, "update")
    return {"taskId": task_id, "status": "queued"}


@router.post("/remove")
def remove_app(request: RemoveRequest, background_tasks: BackgroundTasks) -> dict[str, str]:
    if not request.package_name and not repository.list_installed_components(request.app_id):
        raise HTTPException(status_code=400, detail="packageName is required when app is not tracked locally")
    task_id = _task_id("remove")
    repository.create_task(task_id, "remove", request.app_id, request.app_id)
    background_tasks.add_task(task_runner.run_remove, task_id, request)
    return {"taskId": task_id, "status": "queued"}
