"""运行无参数自检；--input PATH --config PATH 执行日志统计。"""
import argparse
from datetime import datetime, timezone
import json
import os
from pathlib import Path
import subprocess
import sys
from tempfile import TemporaryDirectory


def positive(text):
    if isinstance(text, bool) or not isinstance(text, (str, int)):
        raise ValueError("limit must be an integer")
    value = int(text)
    if value < 1:
        raise ValueError("limit must be positive")
    return value


def execute(argv, environ):
    parser = argparse.ArgumentParser(description="统计指定文件，不依赖当前目录")
    parser.add_argument("--input", type=Path, required=True)
    parser.add_argument("--config", type=Path, required=True)
    parser.add_argument("--limit")
    args = parser.parse_args(argv)
    try:
        config_path = args.config.resolve()
        config = json.loads(config_path.read_text(encoding="utf-8"))
        if not isinstance(config, dict) or set(config) - {"limit"}:
            raise ValueError("config must contain only limit")
        # 显式优先级：命令行 > 环境变量 > 配置文件 > 默认。
        limit = positive(args.limit if args.limit is not None else
                         environ.get("SERIES_LIMIT", config.get("limit", 10)))
        # 输入路径约定相对配置文件目录，而不是相对进程 cwd。
        source = args.input if args.input.is_absolute() else config_path.parent / args.input
        rows = []
        for number, line in enumerate(source.read_text(encoding="utf-8").splitlines(), 1):
            record = json.loads(line)
            at = datetime.fromisoformat(record["at"])
            if at.tzinfo is None or at.utcoffset() is None:
                raise ValueError(f"row {number}: timestamp needs explicit UTC offset")
            rows.append(at.astimezone(timezone.utc).isoformat())
        print(json.dumps({"total": len(rows), "times": rows[:limit]}, ensure_ascii=False))
        return 0
    except (OSError, ValueError, TypeError, KeyError) as exc:
        print(f"input error: {exc}", file=sys.stderr)
        return 2


def self_test():
    script = str(Path(__file__).resolve())
    with TemporaryDirectory() as directory:
        root = Path(directory)
        config = root / "config.json"
        config.write_text('{"limit": 2}', encoding="utf-8")
        source = root / "events.jsonl"
        source.write_text('{"at":"2026-01-01T08:00:00+08:00"}\n'
                          '{"at":"2026-01-01T00:00:00+00:00"}\n', encoding="utf-8")
        other = root / "other"
        other.mkdir()
        environment = dict(os.environ, SERIES_LIMIT="1")
        command = [sys.executable, script, "--input", "events.jsonl", "--config", str(config)]
        outputs = []
        for cwd in (root, other):
            result = subprocess.run(command, cwd=cwd, env=environment, capture_output=True, text=True)
            assert result.returncode == 0, result.stderr
            outputs.append(json.loads(result.stdout))
        assert outputs[0] == outputs[1]
        assert outputs[0] == {"total": 2, "times": ["2026-01-01T00:00:00+00:00"]}
        override = subprocess.run(command + ["--limit", "2"], env=environment,
                                  capture_output=True, text=True)
        assert len(json.loads(override.stdout)["times"]) == 2
        source.write_text('{"at":"2026-01-01T08:00:00"}\n', encoding="utf-8")
        bad = subprocess.run(command, env=environment, capture_output=True, text=True)
        assert bad.returncode == 2 and "explicit UTC offset" in bad.stderr
        config.write_text('{"limit": 0}', encoding="utf-8")
        environment.pop("SERIES_LIMIT", None)
        invalid = subprocess.run(command, env=environment, capture_output=True, text=True)
        assert invalid.returncode == 2 and "positive" in invalid.stderr
        config.write_text('{"limit": 1.5}', encoding="utf-8")
        noninteger = subprocess.run(command, env=environment, capture_output=True, text=True)
        assert noninteger.returncode == 2 and "integer" in noninteger.stderr
        print("25 checks: cwd independent; UTC normalized; precedence; invalid input exit=2")


if __name__ == "__main__":
    if len(sys.argv) == 1:
        self_test()
    else:
        raise SystemExit(execute(sys.argv[1:], os.environ))
