#!/usr/bin/env python3
"""Muse2API Windows Background Service Runner.
Redirects stdout/stderr to data/muse2api.log and runs the uvicorn server.
"""

from __future__ import annotations

import os
import sys
import logging
from pathlib import Path

# Ensure workspace root is in sys.path
BASE_DIR = Path(__file__).resolve().parent
sys.path.insert(0, str(BASE_DIR))

# Create data directory for logs
DATA_DIR = BASE_DIR / "data"
DATA_DIR.mkdir(parents=True, exist_ok=True)
LOG_FILE = DATA_DIR / "muse2api.log"


class StreamToLogger:
    """Redirects writes to both a file and standard stream, conforming to TextIOBase."""

    encoding = "utf-8"
    errors = "replace"

    def __init__(self, log_path: Path, original_stream=None):
        self.log_file = open(log_path, "a", encoding="utf-8", buffering=1)
        self.original_stream = original_stream

    def write(self, buf: str):
        try:
            self.log_file.write(buf)
            self.log_file.flush()
        except Exception:
            pass
        if self.original_stream:
            try:
                self.original_stream.write(buf)
                self.original_stream.flush()
            except Exception:
                pass

    def flush(self):
        try:
            self.log_file.flush()
        except Exception:
            pass
        if self.original_stream:
            try:
                self.original_stream.flush()
            except Exception:
                pass

    def isatty(self) -> bool:
        return False

    def fileno(self) -> int:
        return self.log_file.fileno()

    @property
    def closed(self) -> bool:
        return self.log_file.closed

    def readable(self) -> bool:
        return False

    def writable(self) -> bool:
        return True

    def seekable(self) -> bool:
        return False


def main():
    # Setup log file redirection
    logger_out = StreamToLogger(LOG_FILE, sys.stdout)
    logger_err = StreamToLogger(LOG_FILE, sys.stderr)
    sys.stdout = logger_out
    sys.stderr = logger_err

    from muse2api.config import Settings
    import uvicorn

    settings = Settings()
    settings.ensure_dirs()

    print(f"\n[{settings.log_level}] Starting Muse2API Service on http://{settings.host}:{settings.port}")
    print(f"[{settings.log_level}] Upstream Driver   : {settings.driver}")
    print(f"[{settings.log_level}] Storage Directory : {settings.data_dir.resolve()}")

    uvicorn.run(
        "muse2api.app:create_app",
        factory=True,
        host=settings.host,
        port=settings.port,
        log_level=settings.log_level.lower(),
        access_log=True,
    )


if __name__ == "__main__":
    main()
