#!/usr/bin/env python3
"""
SCH-033 Pass 2: Fix remaining /dev/scheduler/ references.
Patterns:
  1. http://www.aeihawaii.com/dev/scheduler/ -> base_url() or /scheduler/
  2. $_SERVER['DOCUMENT_ROOT']."/dev/scheduler/ -> FCPATH in context
"""
import os
import shutil

BASE = '/var/www/html/dev_scheduler/SCHEDULER'
ENH_DIR = '/var/www/html/dev_scheduler/ENHANCEMENTS/SCH-033_dev_scheduler_cleanup'
ORIG_DIR = os.path.join(ENH_DIR, 'original')
MOD_DIR = os.path.join(ENH_DIR, 'modified')

stats = {'files_modified': 0, 'replacements': 0}

def rel(path):
    return os.path.relpath(path, BASE)

def backup_original(filepath):
    relpath = rel(filepath)
    dest = os.path.join(ORIG_DIR, relpath)
    os.makedirs(os.path.dirname(dest), exist_ok=True)
    if not os.path.exists(dest):
        shutil.copy2(filepath, dest)

def save_modified(filepath):
    relpath = rel(filepath)
    dest = os.path.join(MOD_DIR, relpath)
    os.makedirs(os.path.dirname(dest), exist_ok=True)
    shutil.copy2(filepath, dest)

def process_file(filepath, replacements):
    try:
        with open(filepath, 'r', errors='replace') as f:
            content = f.read()
    except Exception as e:
        print(f"  ERROR reading {filepath}: {e}")
        return 0

    original_content = content
    total = 0

    for old, new in replacements:
        count = content.count(old)
        if count > 0:
            content = content.replace(old, new)
            total += count

    if total > 0:
        backup_original(filepath)
        with open(filepath, 'w') as f:
            f.write(content)
        save_modified(filepath)
        stats['files_modified'] += 1
        stats['replacements'] += total
        print(f"  Modified: {rel(filepath)} ({total} replacements)")

    return total


def main():
    print("=" * 70)
    print("PASS 2: Fix remaining /dev/scheduler/ patterns")
    print("=" * 70)

    # Pattern 1: http://www.aeihawaii.com/dev/scheduler/pdfhtml/createpdfhtml
    # This is used in file_get_contents() to call the app's own URL.
    # Replace with base_url() concatenation:
    # file_get_contents('http://www.aeihawaii.com/dev/scheduler/pdfhtml/createpdfhtml')
    # -> file_get_contents(base_url() . 'pdfhtml/createpdfhtml')
    #
    # But base_url() is a CI function. In single-quoted strings we need to break out.
    # The pattern is always: file_get_contents('http://www.aeihawaii.com/dev/scheduler/...')
    # Replace: 'http://www.aeihawaii.com/dev/scheduler/' with: base_url().'
    # So: file_get_contents('http://www.aeihawaii.com/dev/scheduler/pdfhtml/createpdfhtml')
    # -> file_get_contents(base_url().'pdfhtml/createpdfhtml')

    print("\nStep 1: http://www.aeihawaii.com/dev/scheduler/ in PHP files")

    www_replacement = (
        "'http://www.aeihawaii.com/dev/scheduler/",
        "base_url().'"
    )

    for root, dirs, files in os.walk(BASE):
        dirs[:] = [d for d in dirs if d not in {'_svn', '.svn'}]
        for f in files:
            if not f.endswith('.php'):
                continue
            filepath = os.path.join(root, f)
            try:
                with open(filepath, 'r', errors='replace') as fh:
                    if 'http://www.aeihawaii.com/dev/scheduler/' in fh.read():
                        process_file(filepath, [www_replacement])
            except:
                pass

    # Pattern 2: $_SERVER['DOCUMENT_ROOT']."/dev/scheduler/ in pdfwriting/nempdf.php
    # $_SERVER['DOCUMENT_ROOT']."/dev/scheduler/pdfwriting/tpl.fdf"
    # -> FCPATH . "pdfwriting/tpl.fdf"
    print("\nStep 2: DOCUMENT_ROOT.\"/dev/scheduler/ in nempdf.php")

    nempdf = os.path.join(BASE, 'pdfwriting/nempdf.php')
    if os.path.exists(nempdf):
        process_file(nempdf, [
            ('$_SERVER[\'DOCUMENT_ROOT\']."/dev/scheduler/', 'FCPATH . "'),
        ])

    # Check if there are any remaining
    print("\n" + "=" * 70)
    print(f"PASS 2 SUMMARY: {stats['files_modified']} files, {stats['replacements']} replacements")
    print("=" * 70)


if __name__ == '__main__':
    main()
