from __future__ import annotations

import argparse
import os
from pathlib import Path

from rights_filter.integrations.env_clients import build_provider_runtime
from rights_filter.server.env_file import load_env_file
from rights_filter.server.http_app import build_server
from rights_filter.server.image_store import LocalSubmissionImageStore
from rights_filter.server.sqlite_store import CopyrighterStore


def _provider_readiness(runtime) -> str:
    state = {
        "Naver search": runtime.naver_adapter is not None,
        "Google Vision web detection": runtime.google_adapter is not None,
        "Google custom search": runtime.google_custom_search_adapter is not None,
        "LLM (Ollama)": runtime.llm_assistant is not None,
    }
    return ", ".join(
        f"{name}: {'ready' if ok else 'disabled (no credentials)'}" for name, ok in state.items()
    )


def main() -> None:
    parser = argparse.ArgumentParser(description="Run the local Copyrighter API server.")
    parser.add_argument("--host", default="127.0.0.1")
    parser.add_argument("--port", type=int, default=9500)
    parser.add_argument("--db", default="data/copyrighter.sqlite3")
    parser.add_argument("--images", default="data/submissions")
    parser.add_argument("--static", default="web/operator-gui")
    parser.add_argument("--env", default=".env")
    args = parser.parse_args()

    load_env_file(Path(args.env), os.environ)
    provider_runtime = build_provider_runtime(os.environ)
    print("Provider readiness: " + _provider_readiness(provider_runtime))
    image_store = LocalSubmissionImageStore(Path(args.images))
    store = CopyrighterStore(Path(args.db), provider_runtime=provider_runtime)
    store.initialize()
    store.purge_expired_face_crops()

    auth_token = os.environ.get("COPYRIGHTER_AUTH_TOKEN", "").strip() or None
    if auth_token is None:
        print("WARNING: COPYRIGHTER_AUTH_TOKEN not set — data routes are unauthenticated.")

    server = build_server(
        host=args.host,
        port=args.port,
        store=store,
        image_store=image_store,
        static_dir=Path(args.static),
        auth_token=auth_token,
    )
    print(f"Copyrighter API server listening on http://{args.host}:{args.port}")
    print(f"SQLite DB: {Path(args.db).resolve()}")
    print(f"Submission images: {Path(args.images).resolve()}")
    server.serve_forever()


if __name__ == "__main__":
    main()
