import os
import threading
import time
import logging

from fastapi import FastAPI

from v2_api import compat_router, router as v2_router


app = FastAPI(title="PlytixMage v2")
app.include_router(v2_router)
app.include_router(compat_router)

logger = logging.getLogger("plytixmage-v2")

V2_SYNC_WORKER_ENABLED = os.getenv("V2_SYNC_WORKER_ENABLED", "false").strip().lower() in {
    "1",
    "true",
    "yes",
    "on",
}
V2_SYNC_WORKER_POLL_SECONDS = max(1, int(os.getenv("V2_SYNC_WORKER_POLL_SECONDS", "15")))


def _v2_sync_worker_loop() -> None:
    from settings import load_db_config

    if not load_db_config().enabled:
        logger.info("v2-sync-worker: DB disabled, not starting")
        return

    from app.jobs.v2_sync_worker import run_one

    worker_id = f"embedded-v2-sync-worker-{os.getpid()}"
    logger.info(
        "v2-sync-worker: started embedded loop worker=%s mode=%s poll=%ss",
        worker_id,
        os.getenv("V2_SYNC_EXECUTION_MODE", "simulate").strip().lower() or "simulate",
        V2_SYNC_WORKER_POLL_SECONDS,
    )
    while True:
        try:
            had_work = run_one(worker_id=worker_id)
        except Exception as exc:
            logger.exception("v2-sync-worker: unexpected error: %s", exc)
            had_work = False
        if not had_work:
            time.sleep(V2_SYNC_WORKER_POLL_SECONDS)


@app.on_event("startup")
async def start_v2_sync_worker() -> None:
    if not V2_SYNC_WORKER_ENABLED:
        logger.info("v2-sync-worker: disabled (set V2_SYNC_WORKER_ENABLED=true to enable)")
        return
    worker = threading.Thread(target=_v2_sync_worker_loop, name="v2-sync-worker", daemon=True)
    worker.start()


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(
        "main_v2:app",
        host=os.getenv("UVICORN_HOST", "127.0.0.1"),
        port=int(os.getenv("V2_PORT", "13811")),
        reload=os.getenv("UVICORN_RELOAD", "true").strip().lower() in {"1", "true", "yes", "on"},
    )
