#!/usr/bin/env python3
"""Error Handling Demo - try/except/finally with retries"""

import urllib.request
import time
import json

LOG_FILE = "/tmp/error_handling.log"

def log(message):
    """Log message to file and print"""
    timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
    log_line = f"[{timestamp}] {message}"
    print(log_line)
    with open(LOG_FILE, 'a') as f:
        f.write(log_line + "\n")

def task1_file_handling():
    """Task 1: Try to read nonexistent file, create on error"""
    log("TASK 1: File handling starting")
    filepath = "/tmp/nonexistent.txt"
    
    try:
        log(f"  Attempting to read {filepath}")
        with open(filepath, 'r') as f:
            content = f.read()
        log(f"  Read successful: {content[:50]}")
    except FileNotFoundError:
        log(f"  ERROR: File not found, creating it now")
        with open(filepath, 'w') as f:
            f.write("Created by error_handling.py\n")
        log(f"  File created successfully")
    except Exception as e:
        log(f"  UNEXPECTED ERROR: {type(e).__name__}: {e}")
    finally:
        log("  TASK 1: finally block executed")
    
    return True

def task2_network_retry():
    """Task 2: Network retry logic with 3 attempts"""
    log("TASK 2: Network retry starting")
    url = "http://httpbin.org/delay/1"
    max_attempts = 3
    attempt = 0
    
    while attempt < max_attempts:
        attempt += 1
        log(f"  Attempt {attempt}/{max_attempts} to {url}")
        
        try:
            with urllib.request.urlopen(url, timeout=5) as resp:
                data = json.loads(resp.read().decode())
                log(f"  SUCCESS: Response received")
                return True
        except urllib.error.URLError as e:
            log(f"  ERROR: URLError - {e}")
            if attempt < max_attempts:
                log(f"  Retrying in 1 second...")
                time.sleep(1)
        except Exception as e:
            log(f"  ERROR: {type(e).__name__}: {e}")
            if attempt < max_attempts:
                log(f"  Retrying in 1 second...")
                time.sleep(1)
    
    log(f"  FAILED: All {max_attempts} attempts failed")
    return False

def main():
    log("=== Error Handling Demo Started ===")
    
    # Task 1: File handling with try/except/finally
    task1_file_handling()
    log("")
    
    # Task 2: Network retry with try/except/finally
    success = task2_network_retry()
    log("")
    
    # Cleanup in finally
    log("=== Error Handling Demo Complete ===")
    return success

if __name__ == '__main__':
    main()
