#!/usr/bin/env python3
# /// script
# requires-python = ">=3.12"
# dependencies = [
#     "rich",
# ]
# ///
import builtins
import codecs
import json
import re
import sys
from dataclasses import dataclass
from enum import Enum
from typing import Self

from rich import print
from rich.console import Console
from rich.syntax import Syntax

console = Console()

INFO_LOG_FILE = None

IGNORE_ERRORS = [r'container not found ("admin-tools")']

# Pattern for zap console encoder format:
# 2025-12-10T08:36:15.591-0500    INFO    reflect/value.go:581    message here    {json}
ZAP_PREFIX_PATTERN = re.compile(
    r"^(?P<timestamp>\d{4}-\d{2}-\d{2}T[\d:.+-]+)\s+"
    r"(?P<level>\w+)\s+"
    r"(?P<caller>\S+)\s+"
    r"(?P<msg>.+?)\s*$"
)

# Pattern to match ANSI/terminal escape sequences (CSI, OSC, and simple escapes)
ANSI_ESCAPE_PATTERN = re.compile(
    r"\x1b\[[0-?]*[ -/]*[@-~]"  # CSI sequences (e.g., colors)
    r"|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)"  # OSC sequences (e.g., hyperlinks)
    r"|\x1b[@-Z\\^_]"  # Simple escape sequences
)

# Patterns to detect Go stack trace lines (continuation of error logs)
# Function line: go.temporal.io/sdk/internal.(*baseWorker).runPoller.func1
GO_STACK_FUNC_PATTERN = re.compile(r"^[a-zA-Z0-9_./]+\.\([^)]+\)\.[a-zA-Z0-9_.]+")
# Also matches: go.temporal.io/sdk/internal.SomeFunc
GO_STACK_FUNC_PATTERN2 = re.compile(
    r"^[a-zA-Z][a-zA-Z0-9_]*\.[a-zA-Z0-9_./]+\.[A-Z][a-zA-Z0-9_]*$"
)
# File line:         /Users/dan/go/pkg/mod/go.temporal.io/sdk@v1.38.0/internal/internal_worker_base.go:486
# (may start with tabs or spaces)
GO_STACK_FILE_PATTERN = re.compile(r"^[\t ]+/.+\.go:\d+")


def is_stack_trace_line(line: str) -> bool:
    """Detect if a line looks like a Go stack trace continuation."""
    stripped = line.strip()
    if not stripped:
        return False
    # File path line (indented)
    if GO_STACK_FILE_PATTERN.match(line):
        return True
    # Function name line
    if GO_STACK_FUNC_PATTERN.match(stripped):
        return True
    if GO_STACK_FUNC_PATTERN2.match(stripped):
        return True
    return False


def main():
    for line in sys.stdin:
        try:
            if entry := LogEntry.from_line(line):
                entry.print(raw_line=line)
            elif is_stack_trace_line(line):
                # Print stack trace lines dimmed
                console.print(f"[dim]  {line.rstrip()}[/dim]")
            else:
                builtins.print(line, end="")
        except Exception:
            # Parse error - emit raw (use builtins.print to preserve escape sequences)
            builtins.print(line, end="")


class Level(Enum):
    INFO = 1
    WARN = 2
    ERROR = 3
    IGNORED_ERROR = 4


class Unparseable(Exception):
    pass


@dataclass
class LogEntry:
    record: dict
    # prefix_level: Optional[str] = None
    # prefix_msg: Optional[str] = None
    prefix_level: str | None = None
    prefix_msg: str | None = None
    has_structured_prefix: bool = False  # True if zap timestamp prefix matched

    @classmethod
    # def from_line(cls, line: str) -> Optional[Self]:
    def from_line(cls, line: str) -> Self:
        # Look for '{"' which indicates a JSON object with string keys
        # This avoids false positives like Go's text proto format: outcome:{result:{}}
        if '{"' not in line:
            return None
        brace = line.index('{"')
        record = json.loads(line[brace:])
        if not isinstance(record, dict):
            raise ValueError
        prefix = line[:brace].strip()
        prefix_level = None
        prefix_msg = None
        has_structured_prefix = False
        if prefix:
            record["_prefix"] = prefix
            # Try to parse zap console encoder prefix
            if match := ZAP_PREFIX_PATTERN.match(prefix):
                prefix_level = match.group("level")
                prefix_msg = match.group("msg")
                has_structured_prefix = True
        return cls(record, prefix_level, prefix_msg, has_structured_prefix)

    def __post_init__(self) -> None:
        self.transform()

    def print(self, raw_line: str) -> None:
        # Only consider it a "clearly structured log" if:
        # - It has a proper zap timestamp prefix, OR
        # - It's pure JSON (no prefix) with a level field
        # If there's a non-zap prefix, it's likely an ad-hoc print
        # Note: ignore terminal escape sequences when checking for prefix
        prefix = self.record.get("_prefix", "")
        prefix_without_escapes = ANSI_ESCAPE_PATTERN.sub("", prefix).strip()
        has_meaningful_prefix = bool(prefix_without_escapes)

        # Also consider it structured if the prefix contains INFO/WARN/ERROR keyword
        has_level_keyword = bool(re.search(r"\b(INFO|WARN|ERROR)\b", prefix))
        is_clearly_structured = (
            self.has_structured_prefix
            or (not has_meaningful_prefix and self.record.get("level"))
            or has_level_keyword
        )

        match self.level:
            case Level.IGNORED_ERROR | Level.INFO:
                if INFO_LOG_FILE and is_clearly_structured:
                    with open(INFO_LOG_FILE, "a") as f:
                        print(self.record, file=f)
                elif is_clearly_structured:
                    msg = self.record.get("msg") or self.prefix_msg
                    if msg:
                        print(f"{self.level.name}: {msg}")
                    else:
                        print(self.serialize())
                else:
                    # Has level but not clearly structured - pass through
                    builtins.print(raw_line, end="")
            case Level.WARN | Level.ERROR:
                console.print(style_string(self.serialize(), self.level))
            case _:
                # No recognized level - pass through unchanged (ad-hoc prints)
                builtins.print(raw_line, end="")

    def serialize(self) -> str:
        return (
            json.dumps(self.record, indent=2).replace("\\n", "\n").replace("\\t", "\t")
        )

    def transform(self) -> None:
        for k in ["stacktrace"]:
            if k not in self.record:
                continue
            v = self.record[k]
            if isinstance(v, str):
                v = format_string(v)
            if isinstance(v, list):
                v = list(map(format_string, v))
            self.record[k] = v

    @property
    # def level(self) -> Optional[Level]:
    def level(self) -> Level:
        # Check JSON level first, then fall back to prefix level (zap console format)
        level_str = self.record.get("level", "") or self.prefix_level or ""
        match level_str.lower():
            case "info":
                return Level.INFO
            case "warn" | "warning":
                return Level.WARN
            case "error":
                if err := self.error:
                    for s in IGNORE_ERRORS:
                        if s in err:
                            return Level.IGNORED_ERROR
                return Level.ERROR
            case "debug":
                return Level.INFO  # treat debug like info (condensed)
            case _:
                # Fallback: check if prefix contains INFO/WARN/ERROR as a word
                prefix = self.record.get("_prefix", "")
                if re.search(r"\bINFO\b", prefix):
                    return Level.INFO
                if re.search(r"\bWARN\b", prefix):
                    return Level.WARN
                if re.search(r"\bERROR\b", prefix):
                    return Level.ERROR
                return None

    @property
    # def error(self) -> Optional[str]:
    def error(self) -> str:
        for k in ["Error", "error"]:
            if v := self.record.get(k):
                return v


# def style_string(s: str, level: Optional[Level]) -> Syntax:
def style_string(s: str, level: Level) -> Syntax:
    error_theme = "default"  # happens to apply red style to strings
    # default, sas, manni
    return Syntax(
        s, "json", theme=error_theme if level == Level.ERROR else "sas", word_wrap=True
    )


def format_string(s: str) -> str:
    try:
        return codecs.decode(s, "unicode_escape")
    except Exception:
        return s


if __name__ == "__main__":
    if len(sys.argv) > 1:
        INFO_LOG_FILE = sys.argv[1]
        with open(INFO_LOG_FILE, "w") as f:
            pass

    try:
        main()
    except KeyboardInterrupt:
        pass
