"""OCR module settings.

Environment variables are loaded once by ``app.main`` (``load_dotenv``) before
this module is imported; real environment variables take precedence.
"""

import os
from pathlib import Path

# Gemini API keys: one per pipeline step, so each step has its own quota (requests per minute / per day)
GEMINI_STAGES = ("ocr", "extract", "merge")
_STAGE_KEY_ENV = {"ocr": "OCR_API_KEY", "extract": "EXTRACT_API_KEY", "merge": "MERGE_API_KEY"}


def gemini_api_key(stage: str) -> str:
    """The Gemini API key of a pipeline step ("ocr", "extract" or "merge"), read from OCR_API_KEY,
    EXTRACT_API_KEY or MERGE_API_KEY; "" when it is not set."""
    return os.environ.get(_STAGE_KEY_ENV[stage], "").strip()


DEFAULT_MODEL = os.environ.get("GEMINI_MODEL", "gemini-3.5-flash-lite")

# Thinking budget for the extraction and merge calls (thought tokens are billed as output).
# "auto" or empty (default) sends no thinking config; a number sets thinking_budget (0 = off,
# but gemini-3.5-flash-lite rejects 0, and it does not think by default anyway).
_thinking = os.environ.get("GEMINI_THINKING_BUDGET", "auto").strip().lower()
GEMINI_THINKING_BUDGET = None if _thinking in ("", "auto") else int(_thinking)

# Free tier limits seen on gemini-3.5-flash-lite: 15 requests per minute and 500 requests PER DAY per project
# (a 429 "GenerateRequestsPerDayPerProjectPerModel-FreeTier" means the day is used up; it resets after ~24 h).
RATE_LIMIT_RPM = int(os.environ.get("RATE_LIMIT_RPM", "12"))  # Conservative 12 requests / 60 seconds
MIN_REQUEST_INTERVAL = float(os.environ.get("MIN_REQUEST_INTERVAL", "4.5"))  # Minimum spacing between requests
# Pages of one request processed at the same time. A page call takes 20-60 s, so reaching RATE_LIMIT_RPM
# needs about RATE_LIMIT_RPM x seconds-per-call / 60 calls in flight (12 x 45 / 60 = 9); the shared rate
# limiter still caps the starts per minute, extra threads just wait for their turn.
PAGE_PARALLELISM = max(1, int(os.environ.get("OCR_PAGE_PARALLELISM", "10")))

# Upload limits (per file)
MAX_UPLOAD_MB = float(os.environ.get("MAX_UPLOAD_MB", "50"))
MAX_UPLOAD_BYTES = int(MAX_UPLOAD_MB * 1024 * 1024)

# Every value pages.verification_status / pages.extraction_status can take.
VERIFICATION_STATUSES = ("PENDING", "VERIFIED", "FAILED", "NO_DATA_PAGE", "DEPRECATED")
EXTRACTION_STATUSES = ("PENDING", "COMPLETED", "FAILED", "DEPRECATED")

# Background jobs (/ocr/jobs) are kept in memory for this long after they finish.
JOB_TTL_SEC = int(os.environ.get("JOB_TTL_SEC", "3600"))
# Job queue (jobs.py): jobs of one step that may run at the same time. Every Gemini call still waits for the
# step's rate limiter, so this only lets slow calls overlap (OCR / extraction default: PAGE_PARALLELISM);
# 1 runs that step's jobs strictly one after another. A merge makes many calls itself: one at a time.
JOB_WORKERS = {
    "ocr": max(1, int(os.environ.get("OCR_JOB_WORKERS", str(PAGE_PARALLELISM)))),
    "extract": max(1, int(os.environ.get("EXTRACT_JOB_WORKERS", str(PAGE_PARALLELISM)))),
    "merge": max(1, int(os.environ.get("MERGE_JOB_WORKERS", "1"))),
}
# Jobs that may wait in the queues at once; more are refused with 429.
JOB_QUEUE_MAX = int(os.environ.get("JOB_QUEUE_MAX", "5000"))
# The merge socket (WS /ocr/ws/merge/{code}) is off by default: the hosted server does not pass sockets through, so the
# frontend polls GET /ocr/jobs/{job_id}/events instead (the same messages). Set to 1 to register the socket route again.
MERGE_SOCKET_ENABLED = os.environ.get("MERGE_SOCKET_ENABLED", "").strip().lower() in ("1", "true", "yes", "on")

# Storage Paths (all inside app/ocr/)
BACKEND_DIR = Path(__file__).resolve().parent
DATA_DIR = Path(os.environ.get("OCR_DATA_DIR") or (BACKEND_DIR / "data"))
STORAGE_DIR = Path(os.environ.get("OCR_STORAGE_DIR") or (BACKEND_DIR / "storage"))
UPLOADS_DIR = STORAGE_DIR / "uploads"
PAGES_DIR = STORAGE_DIR / "pages"
OCR_MD_DIR = STORAGE_DIR / "ocr-md-files"
COMPANIES_CATALOG_PATH = DATA_DIR / "companies.json"
DB_PATH = Path(os.environ.get("OCR_DATABASE_PATH") or (DATA_DIR / "financial_ocr.db"))


def init() -> None:
    """Create required directories (called from the app lifespan)."""
    for d in (DB_PATH.parent, UPLOADS_DIR, PAGES_DIR, OCR_MD_DIR):
        d.mkdir(parents=True, exist_ok=True)
