import json
import os
from pathlib import Path


def default_srv_options() -> dict:
    return {
        'pen_pos_up': 65,
        'pen_pos_down': 35,
        'speed_penup': 75,
        'speed_pendown': 35,
        'accel': 60,
        'pen_rate_raise': 75,
        'pen_rate_lower': 50,
        'pen_delay_up': 0,
        'pen_delay_down': 0,
        'const_speed': False,
        'auto_rotate': False,
        'random_start': False,
        'reordering': 4,
        'model': 2,
        'units': 'mm',
    }


def load_srv_options(file):
    try:
        with open(file, 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        return default_srv_options()
    except json.JSONDecodeError:
        return default_srv_options()


def write_srv_options(srv_options, file):
    Path(file).parent.mkdir(parents=True, exist_ok=True)
    with open(file, 'w', encoding='utf-8') as f:
        json.dump(srv_options, f, indent=2)


def ensure_srv_options(file: Path) -> None:
    if Path(file).exists():
        return
    write_srv_options(default_srv_options(), file)


def clamp_int(value, min_value, max_value):
    return max(min_value, min(max_value, value))


def select_file_root(cli_value: str | None) -> Path:
    candidate = cli_value or os.environ.get('ARTWORK_ROOT')
    if not candidate:
        return (Path(os.getcwd()) / 'svg_input').resolve()
    resolved = Path(candidate).expanduser()
    if not resolved.is_absolute():
        resolved = Path(os.getcwd()) / resolved
    return resolved.resolve()


def resolve_dir_path(file_root: Path, rel_path: str | None) -> Path | None:
    if not rel_path:
        rel_path = '.'
    candidate = (file_root / rel_path).resolve()
    if candidate == file_root or file_root in candidate.parents:
        return candidate
    return None


def resolve_file_path(file_root: Path, rel_path: str | None) -> Path | None:
    if not rel_path:
        return None
    candidate = (file_root / rel_path).resolve()
    if candidate == file_root or file_root in candidate.parents:
        return candidate
    return None


# NOTE: this is now handles in axi_server.py
# Filter noisy polling endpoints from Werkzeug request logs.
# class RequestFilter(logging.Filter):
#     def filter(self, record: logging.LogRecord) -> bool:
#         message = record.getMessage()

#         if '"GET /log ' in message or '"GET /axidraw_status ' in message or '"GET /motor_state ' in message:
#             return False
#         return True
