"""Personal Edition settings endpoints not yet owned by a plugin: AI provider
test, AI task prompt preview, and folder pickers. Mounted under ``/api/settings``
alongside the settings plugin's core routes."""

import asyncio
from pathlib import Path

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

from roadmap_framework import session
from app.config import load_config_decrypted

router = APIRouter(prefix="/api/settings", tags=["settings"])


def require_unlocked():
    import app.config as cfg
    if cfg._store is not None and cfg._store.has_encrypted_fields() and not session.is_unlocked():
        raise HTTPException(status_code=403,
                            detail="App is locked. Provide password to unlock.")


@router.get("/ai-task-prompts/{task_type}")
def get_ai_task_prompts(task_type: str):
    require_unlocked()
    if task_type == "context_assistant":
        from app.routers.context_assistant import get_prompts
        return {"task_type": task_type, "steps": get_prompts()}
    raise HTTPException(status_code=404, detail=f"Prompt preview not implemented for task type: {task_type}")


class ListSubfoldersRequest(BaseModel):
    path: str


@router.post("/list-subfolders")
def list_subfolders(req: ListSubfoldersRequest):
    p = Path(req.path)
    if not p.is_dir():
        raise HTTPException(status_code=400, detail=f"Not a directory: {req.path}")
    folders = sorted(
        entry.name
        for entry in p.iterdir()
        if entry.is_dir() and not entry.name.startswith(".")
    )
    return {"folders": folders}


class BrowseFolderRequest(BaseModel):
    initial_dir: str = ""


_FOLDER_PICKER_SCRIPT = '''
import sys, tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
root.attributes("-topmost", True)
kwargs = {"title": "Select folder"}
if len(sys.argv) > 1 and sys.argv[1]:
    from pathlib import Path
    p = Path(sys.argv[1])
    if p.is_dir():
        kwargs["initialdir"] = str(p)
folder = filedialog.askdirectory(**kwargs)
root.destroy()
print(folder or "")
'''


@router.post("/browse-folder")
async def browse_folder(req: BrowseFolderRequest):
    import subprocess, sys
    proc = await asyncio.to_thread(
        subprocess.run,
        [sys.executable, "-c", _FOLDER_PICKER_SCRIPT, req.initial_dir],
        capture_output=True, text=True, timeout=120,
    )
    path = proc.stdout.strip()
    if not path:
        raise HTTPException(status_code=204, detail="No folder selected")
    return {"path": path}
