import importlib.util
import sys
from pathlib import Path

PIPELINE_PATH = Path('/Users/bot1/.hermes/profiles/it/scripts/liangzhu_daily_flow_bot1.py')
PROJECT_ROOT = Path(__file__).resolve().parents[1]


def load_pipeline_module():
    spec = importlib.util.spec_from_file_location('liangzhu_daily_flow_bot1', PIPELINE_PATH)
    module = importlib.util.module_from_spec(spec)
    assert spec.loader is not None
    spec.loader.exec_module(module)
    return module


def test_pipeline_exposes_split_dashboard_verification_hook():
    module = load_pipeline_module()
    assert module.SPLIT_DASHBOARD_URL == 'https://wwyl.yipeng.online/liangzhu-dashboard/'
    assert callable(module.verify_split_dashboard)


def test_notify_dry_run_mentions_muyu_and_lists_weekly_monthly_files(tmp_path):
    module = load_pipeline_module()
    weekly = tmp_path / '良渚电商周报.xlsx'
    monthly = tmp_path / '良渚文化月报.xlsx'
    weekly.write_bytes(b'xlsx-placeholder')
    monthly.write_bytes(b'xlsx-placeholder')
    summary = {
        'run_day': '2026-06-02',
        'qianniu': {'file_count': 40},
        'jd': {'file_count': 5},
        'import': {'raw_rows': 10, 'facts': {}},
        'split_dashboard': {'url': module.SPLIT_DASHBOARD_URL, 'latest_date': '2026-05-31'},
        'weekly': {'skipped': False, 'xlsx': str(weekly)},
        'monthly': {'skipped': False, 'xlsx': str(monthly)},
        'backup': {'skipped': True},
    }
    result = module.notify(summary, dry_run=True)
    assert result['chat_id'] == module.FEISHU_GROUP_CHAT_ID
    assert result['at_open_id'] == 'ou_66def5be461d37087997a8b74347a665'
    assert '<at user_id="ou_66def5be461d37087997a8b74347a665">沐雨</at>' in result['text']
    assert '前后端看板：https://wwyl.yipeng.online/liangzhu-dashboard/' in result['text']
    assert '周报附件：良渚电商周报.xlsx' in result['text']
    assert '月报附件：良渚文化月报.xlsx' in result['text']
    assert [Path(p).name for p in result['files']] == ['良渚电商周报.xlsx', '良渚文化月报.xlsx']


def test_jd_daily_dedup_keeps_one_row_per_store_date_and_prefers_daily_report():
    module = load_pipeline_module()
    rows = [
        {'report_type': '京东分天店铺交易流量报表', 'source_platform': 'jd', 'store_code': 'liangzhu_jd', 'stat_date': '2026-06-01', 'row_number': 1},
        {'report_type': '京东日报', 'source_platform': 'jd', 'store_code': 'liangzhu_jd', 'stat_date': '2026-06-01', 'row_number': 1},
        {'report_type': '京东分天店铺交易流量报表', 'source_platform': 'jd', 'store_code': 'liangzhu_jd', 'stat_date': '2026-06-02', 'row_number': 1},
    ]
    keep = module.jd_daily_keep_keys(rows)
    assert keep == {
        ('liangzhu_jd', '2026-06-01', '京东日报', 1),
        ('liangzhu_jd', '2026-06-02', '京东分天店铺交易流量报表', 1),
    }


def test_jd_export_cleans_previous_xls_before_fresh_export():
    source = PIPELINE_PATH.read_text(encoding='utf-8')
    phase2 = source.split('def phase2_jd', 1)[1].split('def build_stage', 1)[0]
    assert 'shutil.rmtree(out_dir)' in phase2
    assert 'if not skip_export' in phase2


def test_main_replaces_legacy_html_generation_with_split_dashboard(monkeypatch, tmp_path):
    module = load_pipeline_module()
    monkeypatch.setattr(module, 'RUN_BASE', tmp_path)
    monkeypatch.setattr(sys, 'argv', ['liangzhu_daily_flow_bot1.py', '--date', '2026-06-02', '--dry-run', '--skip-backup', '--skip-notify'])
    monkeypatch.setattr(module, 'phase1_qianniu', lambda run_day, skip_export: {'files': [], 'file_count': 40})
    monkeypatch.setattr(module, 'phase2_jd', lambda run_day, skip_export: {'files': [], 'file_count': 5})
    monkeypatch.setattr(module, 'phase3_import', lambda qn, jd, run_day, dry_run: {'dry_run': dry_run, 'raw_rows': 123, 'facts': {}})
    monkeypatch.setattr(module, 'generate_html', lambda run_day: (_ for _ in ()).throw(AssertionError('legacy html should not be generated')))
    monkeypatch.setattr(module, 'deploy_html', lambda path, dry_run: (_ for _ in ()).throw(AssertionError('legacy html should not be deployed')))
    monkeypatch.setattr(module, 'verify_split_dashboard', lambda run_day, dry_run: {'url': module.SPLIT_DASHBOARD_URL, 'latest_date': '2026-05-31', 'health_http': 200, 'day_http': 200})
    monkeypatch.setattr(module, 'generate_weekly', lambda run_day: {'skipped': True, 'reason': 'not_monday'})
    monkeypatch.setattr(module, 'generate_monthly', lambda run_day: {'skipped': True, 'reason': 'not_first_of_month'})

    assert module.main() == 0
    summary = (tmp_path / 'daily_cli_20260602' / 'liangzhu_daily_flow_summary.json').read_text(encoding='utf-8')
    assert 'replaced_by_split_dashboard' in summary
    assert 'https://wwyl.yipeng.online/liangzhu-dashboard/' in summary


def test_project_documents_record_formal_source_cloud_deploy_and_group_notice():
    readme = (PROJECT_ROOT / 'README.md').read_text(encoding='utf-8')
    context = (PROJECT_ROOT / 'PROJECT_CONTEXT.md').read_text(encoding='utf-8')
    deploy = (PROJECT_ROOT / 'docs' / 'DEPLOYMENT.md').read_text(encoding='utf-8')
    assert '/Users/bot1/.hermes/profiles/it/scripts/liangzhu_daily_flow_bot1.py' in context
    assert 'https://wwyl.yipeng.online/liangzhu-dashboard/' in readme
    assert '/srv/liangzhu-dashboard-app' in deploy
    assert 'liangzhu-dashboard.service' in deploy
    assert 'Nginx' in deploy
    assert '万事知答疑群' in deploy
    assert 'ou_66def5be461d37087997a8b74347a665' in deploy
