import sys
import asyncio
from fastapi import FastAPI, Query
from pydantic import BaseModel
from dvc_brokers_scraper.scrapers.runner import run_all, run_one, latest_status

# On Windows, Playwright needs asyncio event loop policy that supports subprocess.
# Windows ProactorEventLoop does not support subprocess; use Selector policy.
if sys.platform.startswith("win"):
    try:
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    except Exception:
        pass
from dvc_brokers_scraper.scheduler import scheduler_get, scheduler_set, scheduler_start
from dvc_brokers_scraper.policy import get_policy, set_policy
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI(title="DVC Broker Scraper", version="2.0.0")
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "http://localhost:5173",
        "http://127.0.0.1:5173",
    ],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class SchedulePatch(BaseModel):
    cron: str

@app.on_event("startup")
def _startup():
    scheduler_start()

@app.get("/status")
def status():
    return latest_status()

@app.get("/brokers")
def brokers():
    from dvc_brokers_scraper.scrapers.registry import list_brokers
    return {"brokers": list_brokers()}

@app.post("/run")
def run(broker: str | None = Query(default=None)):
    return run_one(broker) if broker else run_all()

@app.get("/schedule")
def get_schedule():
    return {"cron": scheduler_get()}

@app.patch("/schedule")
def patch_schedule(s: SchedulePatch):
    scheduler_set(s.cron)
    return {"ok": True, "cron": s.cron}

@app.get("/crawl-policy")
def crawl_policy_get():
    return get_policy()

@app.patch("/crawl-policy")
def crawl_policy_patch(payload: dict):
    set_policy(payload)
    return {"ok": True, "policy": get_policy()}

@app.get("/logs")
def logs():
    return {"detail": "Implement SSE/polling with rotating log file."}
