"""Output logging utilities."""

import sys


class OutputLogger:
    """Captures all terminal output and writes it to both terminal and file."""
    
    def __init__(self, filepath):
        self.terminal = sys.stdout
        self.filepath = filepath
        try:
            self.log = open(filepath, 'w', encoding='utf-8', buffering=1)
            self.file_error = False
        except Exception as e:
            print(f"⚠️  Warning: Could not create log file: {e}", file=sys.stderr)
            self.log = None
            self.file_error = True
    
    def write(self, message):
        try:
            self.terminal.write(message)
            self.terminal.flush()
        except Exception:
            pass
        
        if self.log is not None:
            try:
                self.log.write(message)
                self.log.flush()
            except Exception:
                pass
    
    def flush(self):
        try:
            self.terminal.flush()
        except Exception:
            pass
        if self.log is not None:
            try:
                self.log.flush()
            except Exception:
                pass
    
    def close(self):
        if self.log is not None:
            try:
                self.log.flush()
                self.log.close()
            except Exception:
                pass
    
    def isatty(self):
        try:
            return self.terminal.isatty() if hasattr(self.terminal, 'isatty') else False
        except Exception:
            return False
    
    def fileno(self):
        try:
            return self.terminal.fileno() if hasattr(self.terminal, 'fileno') else -1
        except Exception:
            return -1

