"""Canonical logging imports preserve state, handlers and persistent contracts."""
import importlib
import json
import os
from pathlib import Path
import sqlite3
import subprocess
import sys

from flask import Flask
import pytest


ROOT = Path(__file__).resolve().parents[2]
PAIRS = [
    ("modules.core.request_logging", "modules.core"),
    ("InvestmentWebsite.services.platform_logger", "InvestmentWebsite.services"),
]


def _python(code, tmp_path, *args):
    env = os.environ.copy()
    env["DATA_DIR"] = str(tmp_path / "runtime")
    env["PYTHONPATH"] = str(ROOT)
    env["PYTHONDONTWRITEBYTECODE"] = "1"
    guard = """
import socket
def deny(*args,**kwargs):raise AssertionError('Network forbidden in logging tests')
socket.create_connection=deny;socket.socket.connect=deny;socket.socket.connect_ex=deny
"""
    result = subprocess.run([sys.executable, "-B", "-c", guard + code, *args],
                            cwd=tmp_path, env=env, capture_output=True, text=True, timeout=30)
    assert result.returncode == 0, result.stderr


@pytest.mark.parametrize("module,parent", PAIRS)
@pytest.mark.parametrize("direct_first", [False, True])
def test_canonical_reimports_share_one_state_and_do_not_initialize_runtime(module, parent, direct_first, tmp_path):
    _python("""
import importlib,logging,os,sys
from pathlib import Path
module,parent,first=sys.argv[1:]
before={n:tuple(logging.getLogger(n).handlers) for n in ('','access','access_errors','login')}
def through_parent():
    leaf=module.rsplit('.',1)[1]
    return getattr(__import__(parent,fromlist=[leaf]),leaf)
a=importlib.import_module(module) if first=='True' else through_parent()
b=through_parent() if first=='True' else importlib.import_module(module)
assert a is b and a.__name__==module and sys.modules[module] is a
if hasattr(a,'_last_cleanup_day'):
    marker=object();a._last_cleanup_day=marker;assert b._last_cleanup_day is marker
else:
    assert a.access_logger is b.access_logger
assert before=={n:tuple(logging.getLogger(n).handlers) for n in before}
assert not Path(os.environ['DATA_DIR']).exists()
assert not any(n in sys.modules for n in ('modules.core.app_factory','InvestmentManager.scheduled_jobs','InvestmentManager.export_handoff'))
""", tmp_path, module, parent, str(direct_first))


def test_handlers_rotation_formats_request_records_and_security_headers(tmp_path):
    _python("""
import json,logging,os
from pathlib import Path
from flask import Flask
from modules.core import request_logging as m
import modules.core.request_logging as old
data=Path(os.environ['DATA_DIR'])
m.configure_logging();first={n:tuple(logging.getLogger(n).handlers) for n in ('','access','access_errors','login')}
old.configure_logging();assert first=={n:tuple(logging.getLogger(n).handlers) for n in first}
settings={'':('logs/error.log',90,logging.ERROR,'%(asctime)s %(levelname)s: %(message)s'),
          'access':('logs/website/access.log',30,logging.INFO,'%(message)s'),
          'access_errors':('logs/website/access_errors.log',90,logging.INFO,'%(message)s'),
          'login':('logs/website/login_attempts.log',90,logging.INFO,'%(asctime)s %(message)s')}
for name,(filename,backups,level,fmt) in settings.items():
    logger=logging.getLogger(name);assert logger.level==level
    assert len(logger.handlers)==1
    h=logger.handlers[0];assert Path(h.baseFilename)==data/filename
    assert h.when=='MIDNIGHT' and h.interval==86400 and h.backupCount==0 and h.retention_days==backups
    assert h.encoding=='utf-8' and h.formatter._fmt==fmt
    if name:assert logger.propagate is False
app=Flask('logging-fixture');app.secret_key='fixture-only'
app.before_request(m.start_timer);app.after_request(m.after_request)
@app.route('/<path:path>')
def page(path):return ('fixture',404 if path=='bad' else 200)
client=app.test_client()
for url in ('/ok?token=fixture-secret&x=1','/bad','/api/skip','/static/skip','/sitemap.xml'):
    response=client.get(url,headers={'X-Forwarded-For':'192.0.2.1, 192.0.2.2'})
    assert response.headers['Strict-Transport-Security']=='max-age=31536000; includeSubDomains'
    assert response.headers['X-Frame-Options']=='SAMEORIGIN'
    assert response.headers['X-Content-Type-Options']=='nosniff'
    assert response.headers['Referrer-Policy']=='strict-origin-when-cross-origin'
    assert response.headers['Permissions-Policy']=='geolocation=(), microphone=(), camera=()'
with app.test_request_context('/login'):
    m.start_timer();old.log_login_attempt('fixture-user',True)
logging.getLogger().error('fixture-error')
for handlers in first.values():
    for h in handlers:h.flush()
records=[json.loads(s) for s in (data/'logs/website/access.log').read_text(encoding='utf-8').splitlines()]
assert [s['path'] for s in records]==['/ok','/bad']
assert records[0]['query']=='token&x' and records[0]['ip']=='-' and records[0]['user_agent']=='-'
assert set(records[0])=={'datetime','request_id','ip','method','path','query','status','referer','lang','response_time_ms','user_agent'}
errors=[json.loads(s) for s in (data/'logs/website/access_errors.log').read_text(encoding='utf-8').splitlines()]
assert len(errors)==1 and errors[0]['status']==404 and errors[0]['ip']=='192.0.2.1'
login=(data/'logs/website/login_attempts.log').read_text(encoding='utf-8')
assert 'LOGIN_ATTEMPT | SUCCESS | USER="fixture-user"' in login and 'SESSION=' not in login
assert 'REQUEST_ID=' in login and 'USER_AGENT=' in login
assert 'ERROR: fixture-error' in (data/'logs/error.log').read_text(encoding='utf-8')
for logger in [logging.getLogger(n) for n in first]:
    for h in list(logger.handlers):logger.removeHandler(h);h.close()
""", tmp_path)


def test_platform_payload_wal_report_mode_and_alias_state(monkeypatch, tmp_path):
    from InvestmentWebsite.services import platform_logger as m
    old = importlib.import_module("InvestmentWebsite.services.platform_logger")
    path = tmp_path / "platform_logs.db"
    monkeypatch.setattr(m.storage_paths, "platform_logs_db_path", lambda: path)
    monkeypatch.setattr(m, "_last_cleanup_day", None)
    app = Flask(__name__)
    app.config["PLATFORM_LOG_RETENTION_MODE"] = "report"
    with app.app_context():
        conn = m._get_connection()
        assert conn.execute("PRAGMA journal_mode").fetchone()[0] == "wal"
        assert conn.execute("PRAGMA synchronous").fetchone()[0] == 1
        m._ensure_schema(conn)
        conn.execute("INSERT INTO platform_logs (created_at,log_type,payload) VALUES ('2000-01-01','api','{}')")
        conn.commit()
        conn.close()
        original = m._get_connection
        trace, opened = [], []

        def traced():
            connection = original()
            connection.set_trace_callback(trace.append)
            opened.append(connection)
            return connection

        monkeypatch.setattr(m, "_get_connection", traced)
        try:
            old.save_platform_log({"path": "/fixture", "status": "ok", "label": "Łódź"}, "fixture")
            m.save_platform_log({"event": "second"})
            assert old._last_cleanup_day is m._last_cleanup_day
            assert not any(sql.startswith("DELETE FROM platform_logs") for sql in trace)
        finally:
            for connection in opened:
                connection.close()
    with sqlite3.connect(path) as conn:
        rows = conn.execute("SELECT log_type,path,status,payload FROM platform_logs ORDER BY id").fetchall()
    assert [row[:3] for row in rows] == [
        ("api", None, None),
        ("fixture", "/fixture", "ok"),
        ("general", None, None),
    ]
    assert json.loads(rows[1][3])["label"] == "Łódź"


def test_platform_log_exception_contract(monkeypatch):
    from InvestmentWebsite.services import platform_logger as m
    app = Flask(__name__)
    messages = []
    monkeypatch.setattr(app.logger, "error", lambda message, *args: messages.append(message % args if args else message))

    def fail():
        raise OSError("fixture failure")

    monkeypatch.setattr(m, "_get_connection", fail)
    with app.app_context():
        assert m.save_platform_log({"event": "fixture"}) is None
    assert messages == ["Log write error: fixture failure"]


def test_local_request_logs_do_not_move_platform_database(tmp_path):
    # A fresh process exercises the real resolver, before the session fixture
    # redirects the platform DB for unrelated HTTP tests.
    _python("""
import os,sys
from pathlib import Path
from modules.core import storage_paths
data=Path(os.environ['DATA_DIR']);text=Path(sys.argv[1])
before=storage_paths.platform_logs_db_path()
os.environ['REQUEST_LOG_DIR']=str(text)
assert storage_paths.website_logs_dir()==text/'website'
assert storage_paths.error_log_path()==text/'error.log'
assert storage_paths.platform_logs_db_path()==before==data/'databases/platform_logs.db'
assert not data.exists() and not text.exists()
""", tmp_path, str(tmp_path / "text-logs"))


@pytest.mark.parametrize("value", ["relative-logs", "../logs"])
def test_request_log_override_rejects_relative_paths(monkeypatch, value):
    from modules.core import storage_paths
    monkeypatch.setenv("REQUEST_LOG_DIR", value)
    with pytest.raises(ValueError, match="REQUEST_LOG_DIR"):
        storage_paths.website_logs_dir()


def test_empty_request_log_override_keeps_existing_paths(monkeypatch, tmp_path):
    from modules.core import storage_paths
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    monkeypatch.setenv("REQUEST_LOG_DIR", "")
    assert storage_paths.website_logs_dir() == tmp_path / "logs/website"
    assert storage_paths.error_log_path() == tmp_path / "logs/error.log"
