"""Short-lived cron executor. Importing this module never starts or writes anything."""
import argparse
from contextlib import contextmanager, redirect_stdout
import json
import logging
from logging.handlers import RotatingFileHandler
import math
import os
import re
import time
from uuid import uuid4

from modules.core import storage_paths
# The state/lock primitives live in scheduler_state (S4.4); the historical names stay available here as the same objects.
from InvestmentManager.scheduler_state import SchedulerError, runner_lock
from InvestmentManager.scheduler_state import directory as _directory, json_object as _json_object, read as _read, write as _write

DEFAULT_CONFIG = {"version": 1, "resize_images": {"enabled": False, "interval_minutes": 5}}
OUTCOMES = {"running", "success", "error", "image_lock_busy", "interrupted"}
HISTORY_LIMIT = 30
EVENT_LIMIT = 100
RUN_ID = re.compile(r'^[0-9a-f]{32}$')
STAT_KEYS = {'offers_scanned', 'conversions', 'conversion_skips', 'resizes', 'thumbnails',
             'thumbnail_skips', 'missing_thumbnail_sources', 'errors'}


def _config(value):
    if (not isinstance(value, dict) or set(value) != {"version", "resize_images"}
            or type(value["version"]) is not int or value["version"] != 1):
        raise SchedulerError("invalid_config.json")
    job = value["resize_images"]
    if (not isinstance(job, dict) or set(job) != {"enabled", "interval_minutes"}
            or type(job["enabled"]) is not bool
            or type(job["interval_minutes"]) is not int or not 1 <= job["interval_minutes"] <= 1440):
        raise SchedulerError("invalid_config.json")
    return value


def _number(value):
    try:
        return type(value) in (int, float) and math.isfinite(value) and value >= 0
    except OverflowError:
        return False


def _state(value):
    if value is None:
        return None
    if (not isinstance(value, dict) or set(value) != {"version", "next_due", "last_success", "attempt"}
            or type(value["version"]) is not int or value["version"] != 1 or not _number(value["next_due"])
            or (value["last_success"] is not None and not _number(value["last_success"]))):
        raise SchedulerError("invalid_state.json")
    attempt = value["attempt"]
    if attempt is not None:
        if (not isinstance(attempt, dict)
                or set(attempt) != {"id", "started_at", "finished_at", "duration_seconds", "outcome", "stats"}
                or not isinstance(attempt["id"], str) or not RUN_ID.fullmatch(attempt["id"])
                or not _number(attempt["started_at"]) or not isinstance(attempt["outcome"], str)
                or attempt["outcome"] not in OUTCOMES
                or (attempt["finished_at"] is not None and not _number(attempt["finished_at"]))
                or (attempt["duration_seconds"] is not None and not _number(attempt["duration_seconds"]))
                or not isinstance(attempt["stats"], dict)
                or any(not isinstance(k, str) or len(k) > 64 or type(v) is not int or v < 0
                       for k, v in attempt["stats"].items())):
            raise SchedulerError("invalid_state.json")
        if (attempt["outcome"] == "running") != (attempt["finished_at"] is None):
            raise SchedulerError("invalid_state.json")
    return value


def _runs_directory(create=False):
    path = _directory(create=create) / 'runs'
    if path.is_symlink() or (hasattr(path, 'is_junction') and path.is_junction()):
        raise SchedulerError('unsafe_history_path')
    if create:
        path.mkdir(mode=0o700, exist_ok=True)
    return path


def _run_files():
    path = _runs_directory()
    if not path.exists():
        return []
    # Bound scanning even if a private directory has been accidentally polluted.
    result = []
    with os.scandir(path) as entries:
        for index, entry in enumerate(entries):
            if index >= HISTORY_LIMIT + 20:
                raise SchedulerError('history_directory_limit')
            if re.fullmatch(r'[0-9a-f]{32}\.json', entry.name):
                if entry.is_symlink() or not entry.is_file(follow_symlinks=False):
                    raise SchedulerError('unsafe_history_path')
                result.append(entry.name)
    return result


def _safe_attempt(attempt):
    _state({'version': 1, 'next_due': 0, 'last_success': None, 'attempt': attempt})
    if attempt is None:
        raise SchedulerError('invalid_history')
    return dict(attempt, stats={key: value for key, value in attempt['stats'].items() if key in STAT_KEYS})


def _safe_event(level, message, timestamp):
    """Allowlist of actual executor messages; never expose arbitrary exception/output text."""
    safe = None
    severity = 'info'
    for prefix in ('Unsafe image conversion skipped:', 'Failed to process ',
                   'Failed to select thumbnail source:', 'Failed to create or update thumbnail for '):
        if message.startswith(prefix):
            safe = prefix.rstrip() + ' [szczegóły pliku i wyjątku ukryte]'
            severity = 'warning' if prefix.startswith('Unsafe') else 'error'
            break
    if message.startswith('Successfully resized:'):
        safe = 'Successfully resized: [dane pliku ukryte]'
    elif message.startswith('Offers root:'):
        safe = 'Offers root: [ścieżka ukryta]'
    elif message == 'Another resize_images.py run is already active; exiting.':
        safe, severity = message, 'warning'
    elif message == 'End of resizing':
        safe = message
    elif re.fullmatch(r'resize_images start attempt=[0-9a-f]{32}', message):
        safe = message
    elif re.fullmatch(r'resize_images failed attempt=[0-9a-f]{32} category=[A-Za-z_][A-Za-z_0-9]{0,63}', message):
        # Exception classes can be arbitrary too; only the fixed prefix and ID are public.
        safe, severity = message.split(' category=')[0] + ' [typ i treść wyjątku ukryte]', 'error'
    elif re.fullmatch(r'resize_images failed attempt=[0-9a-f]{32} \[typ i treść wyjątku ukryte\]', message):
        safe, severity = message, 'error'
    elif re.match(r'^resize_images result=(success|error|image_lock_busy)(?: stats=|$)', message):
        safe = message.split(' stats=')[0]
    elif message.startswith('Summary: '):
        fields = message[9:].split(', ')
        allowed = STAT_KEYS | {'offers'}
        if all(re.fullmatch(r'[a-z_]+=\d{1,12}', field) and field.split('=')[0] in allowed for field in fields):
            safe = message
    if safe is None:
        safe = '[treść komunikatu wykonawcy ukryta]'
    if level >= logging.ERROR:
        severity = 'error'
    elif level >= logging.WARNING:
        severity = 'warning'
    return {'at': timestamp, 'level': severity, 'message': safe[:500]}


def _read_run(run_id):
    if not isinstance(run_id, str) or not RUN_ID.fullmatch(run_id):
        raise SchedulerError('invalid_run_id')
    _runs_directory()
    record = _read('runs/' + run_id + '.json', None)
    if record is None:
        raise SchedulerError('history_not_found')
    if (not isinstance(record, dict) or set(record) != {'version', 'attempt', 'events', 'truncated'}
            or type(record['version']) is not int or record['version'] != 1
            or type(record['truncated']) is not bool or not isinstance(record['events'], list)
            or len(record['events']) > EVENT_LIMIT):
        raise SchedulerError('invalid_history')
    attempt = _safe_attempt(record['attempt'])
    if attempt['id'] != run_id:
        raise SchedulerError('invalid_history')
    events = []
    for event in record['events']:
        if (not isinstance(event, dict) or set(event) != {'at', 'level', 'message'}
                or not _number(event['at']) or event['level'] not in ('info', 'warning', 'error')
                or not isinstance(event['message'], str) or len(event['message']) > 500):
            raise SchedulerError('invalid_history')
        # Sanitize even persisted entries, including tampered/old content; redaction is idempotent.
        level = {'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR}[event['level']]
        events.append(_safe_event(level, event['message'], event['at']))
    return dict(record, attempt=attempt, events=events)


def _save_run(attempt, events, truncated=False):
    """Single archive for both UIs. Diagnostics failures never change job results."""
    try:
        _runs_directory(create=True)
        record = {'version': 1, 'attempt': _safe_attempt(attempt), 'events': events[-EVENT_LIMIT:],
                  'truncated': truncated or len(events) > EVENT_LIMIT}
        if len(json.dumps(record, ensure_ascii=True, allow_nan=False).encode('ascii')) > 65536:
            return False
        # Retention happens only in the CLI while holding runner_lock; HTTP never removes files.
        files = _run_files()
        ordered = []
        for name in files:
            try:
                started = _read_run(name[:-5])['attempt']['started_at']
            except (OSError, SchedulerError):
                started = -1  # Corrupt old records can be retired by the bounded writer.
            ordered.append((started, name))
        survivors = HISTORY_LIMIT - (0 if attempt['id'] + '.json' in files else 1)
        for _, name in sorted(ordered, reverse=True)[survivors:]:
            if name != attempt['id'] + '.json':
                (_runs_directory() / name).unlink()
        _write('runs/' + attempt['id'] + '.json', record)
        return True
    except (OSError, SchedulerError, ValueError, RecursionError):
        return False


def diagnostics(run_id=None):
    """Bounded, read-only diagnostics. Does not acquire any execution/image/input lock."""
    if run_id is not None:
        return _read_run(run_id)
    current = status()
    warnings, records = [], {}
    for name in _run_files():
        try:
            record = _read_run(name[:-5])
            records[name[:-5]] = {'attempt': record['attempt'], 'truncated': record['truncated'],
                                 'issues': [event for event in record['events'] if event['level'] != 'info'][-5:],
                                 'log_available': True}
        except (OSError, SchedulerError):
            warnings.append('Pominięto niedostępny lub uszkodzony zapis przebiegu.')
    latest = current['state']['attempt'] if current['state'] else None
    if latest:
        # The durable execution state is authoritative if final history persistence failed.
        entry = records.get(latest['id'])
        if not entry or entry['attempt'] != _safe_attempt(latest):
            warnings.append('Historia ostatniej próby jest niepełna; wynik pochodzi ze stanu wykonawcy.')
        records[latest['id']] = dict(entry or {'truncated': False, 'issues': [], 'log_available': False},
                                     attempt=_safe_attempt(latest))
    return dict(current, runs=sorted(records.values(), key=lambda row: row['attempt']['started_at'], reverse=True)[:HISTORY_LIMIT],
                warnings=warnings, retention=HISTORY_LIMIT)


def status():
    """Read-only: no creation, recovery, locks or job imports on HTTP GET."""
    config = _config(_read("config.json", DEFAULT_CONFIG))
    state = _state(_read("state.json", None))
    if config["resize_images"]["enabled"] and state is None:
        raise SchedulerError("missing_state")
    return {"config": config, "state": state}


def configure(value, *, now=None):
    value = _config(value)
    now = time.time() if now is None else now
    with runner_lock() as acquired:
        if not acquired:
            raise SchedulerError("runner_busy")
        previous = status()  # Corrupt files require explicit operator recovery; never overwrite silently.
        state = previous["state"]
        changed = value != previous["config"]
        if state is None:
            state = {"version": 1, "next_due": 0, "last_success": None, "attempt": None}
        if changed or state["next_due"] == 0:
            interval = value["resize_images"]["interval_minutes"] * 60
            state["next_due"] = (int(now // interval) + 1) * interval
        # Write state first, so interrupted first-time enable cannot leave an enabled job with no state.
        _write("state.json", state)
        _write("config.json", value)
    return status()


class _LogStream:
    def __init__(self, logger):
        self.logger = logger

    def write(self, text):
        for line in text.splitlines():
            if line.strip():
                self.logger.info("%s", line)
        return len(text)

    def flush(self):
        pass


class _RunLogHandler(logging.Handler):
    def __init__(self, events):
        super().__init__()
        self.events = events

    def emit(self, record):
        # Keep one extra entry to remember truncation; bounded regardless of job output volume.
        self.events.append(_safe_event(record.levelno, record.getMessage(), record.created))
        if len(self.events) > EVENT_LIMIT + 1:
            del self.events[0]


@contextmanager
def _job_log(attempt, events):
    path = _directory() / "scheduler.log"
    if path.is_symlink():
        raise SchedulerError("unsafe_scheduler_path")
    logger = logging.Logger("investment.scheduler")
    handler = RotatingFileHandler(path, maxBytes=1024 * 1024, backupCount=3, encoding="utf-8")
    handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))
    logger.addHandler(handler)
    logger.addHandler(_RunLogHandler(events))
    try:
        yield logger
    finally:
        handler.close()
        _save_run(attempt, events)


def _tick_images(*, now=None):
    """Consume at most one due slot. Crashes never automatically replay that slot."""
    now = time.time() if now is None else now
    with runner_lock() as acquired:
        if not acquired:
            return {"outcome": "runner_busy"}
        current = status()
        config, state = current["config"]["resize_images"], current["state"]
        # Holding the runner lock proves no scheduler execution is still active.
        if state and state["attempt"] and state["attempt"]["outcome"] == "running":
            state["attempt"].update(outcome="interrupted", finished_at=now, duration_seconds=None)
            _write("state.json", state)
            try:
                old = _read_run(state['attempt']['id'])
            except (OSError, SchedulerError):
                old = {'events': [], 'truncated': False}
            _save_run(state['attempt'], old['events'], old['truncated'])
            return {"outcome": "interrupted"}
        if not config["enabled"]:
            return {"outcome": "disabled"}
        if now < state["next_due"]:
            return {"outcome": "not_due"}
        state["next_due"] = (int(now // (config["interval_minutes"] * 60)) + 1) * config["interval_minutes"] * 60
        attempt = {"id": uuid4().hex, "started_at": now, "finished_at": None,
                   "duration_seconds": None, "outcome": "running", "stats": {}}
        state["attempt"] = attempt
        _write("state.json", state)  # Durable before touching images, including the consumed slot.
        events = []
        _save_run(attempt, events)
        started = time.perf_counter()
        try:
            with _job_log(attempt, events) as logger:
                logger.info("resize_images start attempt=%s", attempt["id"])
                # Lazy import only in CLI, never in HTTP or app startup.
                from tools import resize_images
                with redirect_stdout(_LogStream(logger)):
                    with resize_images.process_lock(storage_paths.offers_root_dir()) as image_lock:
                        if not image_lock:
                            attempt["outcome"] = "image_lock_busy"
                        else:
                            attempt["stats"] = resize_images.run()
                            attempt["outcome"] = "error" if attempt["stats"]["errors"] else "success"
                logger.info("resize_images result=%s stats=%s", attempt["outcome"], attempt["stats"])
        except Exception as exc:
            # Never expose private paths or exception details in the API/state/stdout.
            attempt["outcome"] = "error"
            # Stable diagnostic category only; detailed image errors are already in the job log.
            try:
                with _job_log(attempt, events) as logger:
                    logger.error("resize_images failed attempt=%s category=%s", attempt["id"], type(exc).__name__)
            except (OSError, SchedulerError):
                pass
        elapsed = time.perf_counter() - started
        attempt.update(finished_at=now + elapsed, duration_seconds=elapsed)
        if attempt["outcome"] == "success":
            state["last_success"] = attempt["finished_at"]
        _state(state)
        _write("state.json", state)
        saved = _save_run(attempt, events)
        return {"outcome": attempt["outcome"], "attempt": attempt, 'diagnostics_saved': saved}


def _tick_exports(images):
    """Export phase after the image phase; every phase takes the runner lock itself.

    runner_busy skips it. A broken image configuration/state still allows recovery and ACK-only,
    never a new delivery. Returns None when exports are idle (no schema and dispatch off), so the
    historical tick response is unchanged until the export store exists.
    """
    outcome = images.get("outcome")
    if outcome == "runner_busy":
        return None
    from InvestmentManager.integrator import export_job_runner
    mode = "recovery_and_ack_only" if outcome == "scheduler_error" else "full"
    try:
        return export_job_runner.tick_one(mode=mode)
    except SchedulerError as exc:
        return {"outcome": "error", "code": str(exc)}
    except OSError:
        return {"outcome": "error", "code": "storage_error"}
    except Exception:
        return {"outcome": "error", "code": "exports_error"}


def tick(*, now=None):
    """Image phase, then the export phase. Top-level fields stay those of the image phase.

    Errors of the image phase still propagate (as before); the export phase has then already
    run in recovery/ACK-only mode and its result travels on the exception as ``exports``.
    """
    try:
        result = _tick_images(now=now)
    except (SchedulerError, OSError) as exc:
        exc.exports = _tick_exports({"outcome": "scheduler_error"})
        raise
    exports = _tick_exports(result)
    if exports is not None:
        result = dict(result, exports=exports)
    return result


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("operation", choices=["tick"])
    parser.parse_args(argv)
    try:
        result = tick()
    except SchedulerError as exc:
        result = {"outcome": "scheduler_error", "code": str(exc)}
        if getattr(exc, "exports", None) is not None:
            result["exports"] = exc.exports
    except OSError as exc:
        result = {"outcome": "scheduler_error", "code": "storage_error"}
        if getattr(exc, "exports", None) is not None:
            result["exports"] = exc.exports
    print(json.dumps(result))
    failed = (result["outcome"] in {"error", "scheduler_error", "interrupted"}
              or result.get("exports", {}).get("outcome") == "error")
    return 1 if failed else 0


if __name__ == "__main__":
    raise SystemExit(main())
