#!/usr/bin/env python3
"""Tests for writing data/config.php from the auth_client_secret CI secret.

Fake secrets below are test fixtures only. The real secret is never used here.
This file prints only pass/fail text, never a generated config or a secret.
"""
from __future__ import annotations

import os
import subprocess
import sys
import tempfile
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from deploy import (  # noqa: E402
    auth_config_php,
    deploy_commands,
    php_single_quoted,
)

FAKE = 'test-secret-value-NOT-FOR-PRODUCTION'
FAKE_QUOTED = "it's a \\secret with 'quotes'"
ENV = {
    'timftphost': 'ftp://example.test',
    'timftpuser': 'u',
    'timftppassword': 'p',
}


def check(cond, msg):
    if not cond:
        raise SystemExit('FAIL: ' + msg)


def test_empty_secret():
    check(auth_config_php({}) is None, 'unset → None')
    check(auth_config_php({'auth_client_secret': ''}) is None, 'empty → None')
    check(auth_config_php({'auth_client_secret': '   '}) is None, 'whitespace → None')


def test_php_quoting():
    check(php_single_quoted('hello') == "'hello'", 'plain')
    check(php_single_quoted("it's") == r"'it\'s'", 'quote')
    check(php_single_quoted('a\\b') == r"'a\\b'", 'backslash')


def test_generated_php_evaluates():
    php = auth_config_php({'auth_client_secret': FAKE_QUOTED, 'auth_client_id': ''})
    check(php is not None, 'php generated')
    check('projects.timfalken.com' in php, 'default client_id')
    check('https://projects.timfalken.com/allianties' in php, 'base_url')
    php2 = auth_config_php({
        'auth_client_secret': FAKE,
        'auth_client_id': 'other.example',
    })
    check('other.example' in php2, 'optional auth_client_id')

    cfg = Path(tempfile.mkstemp(suffix='.php')[1])
    wrp = Path(tempfile.mkstemp(suffix='.php')[1])
    cfg.write_text(php)
    # Wrapper prints only safe fields and a MATCH flag; never the secret.
    wrp.write_text(
        "<?php\n"
        "$c = require $argv[1];\n"
        "echo $c['client_id'], chr(10), $c['base_url'], chr(10), "
        "strlen($c['client_secret']), chr(10), "
        "($c['client_secret'] === $argv[2] ? 'MATCH' : 'MISMATCH'), chr(10);\n"
    )
    try:
        result = subprocess.run(
            ['php', str(wrp), str(cfg), FAKE_QUOTED],
            capture_output=True,
            text=True,
            check=False,
        )
    finally:
        cfg.unlink(missing_ok=True)
        wrp.unlink(missing_ok=True)
    if result.returncode != 0:
        # Redact any accidental secret material before printing.
        blob = (result.stdout + '\n' + result.stderr).replace(FAKE_QUOTED, '[FAKE]').replace(FAKE, '[FAKE]')
        raise SystemExit('FAIL: php exit %s: %s' % (result.returncode, blob[:300]))
    lines = result.stdout.strip().splitlines()
    check(len(lines) >= 4, 'php output lines')
    check(lines[0] == 'projects.timfalken.com', 'client_id eval')
    check(lines[1] == 'https://projects.timfalken.com/allianties', 'base_url eval')
    check(lines[3] == 'MATCH', 'secret round-trip')
    check(FAKE_QUOTED not in result.stdout, 'php test stdout leaked secret')


def test_lftp_script_has_no_secret():
    cmds = '\n'.join(deploy_commands(ENV, '/var/www/allianties', Path('build')))
    check('--delete' not in cmds, 'no --delete')
    check('--exclude-glob "**/config.php"' in cmds, 'mirror excludes config')
    check('--exclude-glob "data/**"' in cmds, 'mirror excludes data')
    check(' -o data/config.php' not in cmds, 'no put without secret path')
    check('data/.htaccess' in cmds, 'htaccess still put')

    path = '/tmp/allianties-auth-XXXX/config.php'
    cmds2 = '\n'.join(
        deploy_commands(ENV, '/var/www/allianties', Path('build'), auth_config_path=path)
    )
    check(' -o data/config.php' in cmds2, 'put when path given')
    check(path in cmds2, 'local path in put')
    check(FAKE not in cmds2 and FAKE_QUOTED not in cmds2, 'secret not in lftp script')
    check('--delete' not in cmds2, 'no --delete with config put')


def main():
    test_empty_secret()
    test_php_quoting()
    test_generated_php_evaluates()
    test_lftp_script_has_no_secret()
    print('auth-config ok')
    return 0


if __name__ == '__main__':
    sys.exit(main())
