"""
MOPS 公司清單同步工具
透過 autocomplete API 取得所有上市、上櫃、興櫃、公開發行公司清單
"""
import sys
sys.stdout.reconfigure(encoding='utf-8')

import json
import os
from datetime import datetime
from pathlib import Path

# Playwright 腳本模板 - 抓取 autocomplete 清單
PLAYWRIGHT_SCRIPT = '''
const { chromium } = require('playwright');

const TARGET_URL = 'https://mopsov.twse.com.tw/mops/web/t05st03';

(async () => {
  const browser = await chromium.launch({ headless: true });
  const page = await browser.newPage();
  const allCompanies = new Map();

  try {
    await page.goto(TARGET_URL, { waitUntil: 'networkidle', timeout: 30000 });

    // 輸入 0-9 來觸發 autocomplete，取得所有公司
    const searchTerms = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

    for (const term of searchTerms) {
      const input = await page.locator('input#co_id');
      await input.fill('');
      await input.type(term, { delay: 50 });
      await page.waitForTimeout(1500);

      const companies = await page.evaluate(() => {
        const items = document.querySelectorAll('[id^="autoDiv-"]');
        const results = [];
        items.forEach(item => {
          const code = item.value;
          const text = item.parentElement?.innerText?.trim() || '';
          const match = text.match(/^(\\d+)\\s+(.+)$/);
          if (match) {
            results.push({ code: match[1], name: match[2] });
          }
        });
        return results;
      });

      companies.forEach(c => allCompanies.set(c.code, c.name));

      // 顯示進度
      console.error(`搜尋 "${term}": 找到 ${companies.length} 間，累計 ${allCompanies.size} 間`);
    }

    // 輸出結果
    const result = {
      total: allCompanies.size,
      fetched_at: new Date().toISOString(),
      companies: Array.from(allCompanies.entries()).map(([code, name]) => ({ code, name }))
    };

    console.log(JSON.stringify(result));

  } catch (error) {
    console.error(JSON.stringify({ error: error.message }));
  } finally {
    await browser.close();
  }
})();
'''

def get_project_dir():
    """取得專案目錄"""
    return Path(__file__).parent

def get_data_dir():
    """取得資料儲存目錄"""
    data_dir = get_project_dir() / "data"
    data_dir.mkdir(exist_ok=True)
    return data_dir

def sync_companies() -> dict:
    """
    同步公司清單

    Returns:
        包含所有公司代碼和名稱的字典
    """
    import subprocess
    import tempfile

    print("正在從 MOPS 同步公司清單...")
    print("（透過 autocomplete API，輸入 0-9 取得所有公司）\n")

    # 建立暫時腳本
    with tempfile.NamedTemporaryFile(mode='w', suffix='.js', delete=False, encoding='utf-8') as f:
        f.write(PLAYWRIGHT_SCRIPT)
        script_path = f.name

    try:
        # 執行 Playwright 腳本
        skill_dir = Path.home() / ".claude" / "plugins" / "marketplaces" / "playwright-skill" / "skills" / "playwright-skill"

        result = subprocess.run(
            ['node', 'run.js', script_path],
            cwd=skill_dir,
            capture_output=True,
            text=True,
            timeout=180  # 3 分鐘超時
        )

        # 顯示進度訊息
        if result.stderr:
            for line in result.stderr.strip().split('\n'):
                if '搜尋' in line:
                    print(line)

        # 解析輸出
        output_lines = result.stdout.strip().split('\n')
        json_line = None

        for line in output_lines:
            if line.strip().startswith('{') and '"total"' in line:
                json_line = line
                break

        if json_line:
            return json.loads(json_line)
        else:
            return {"error": "無法解析輸出", "stdout": result.stdout[:500]}

    finally:
        os.unlink(script_path)

def load_existing_companies() -> dict:
    """載入現有公司清單"""
    companies_file = get_data_dir() / "companies.json"
    if companies_file.exists():
        with open(companies_file, 'r', encoding='utf-8') as f:
            return json.load(f)
    return None

def save_companies(data: dict):
    """儲存公司清單"""
    companies_file = get_data_dir() / "companies.json"
    with open(companies_file, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    return companies_file

def compare_companies(old_data: dict, new_data: dict) -> dict:
    """比較新舊公司清單，找出差異"""
    old_codes = {c['code'] for c in old_data.get('companies', [])}
    new_codes = {c['code'] for c in new_data.get('companies', [])}

    # 新增的公司
    added_codes = new_codes - old_codes
    added = [c for c in new_data['companies'] if c['code'] in added_codes]

    # 移除的公司
    removed_codes = old_codes - new_codes
    removed = [c for c in old_data['companies'] if c['code'] in removed_codes]

    return {
        "added": added,
        "removed": removed,
        "old_total": len(old_codes),
        "new_total": len(new_codes)
    }

def main():
    import argparse

    parser = argparse.ArgumentParser(description='MOPS 公司清單同步工具')
    parser.add_argument('--force', '-f', action='store_true', help='強制重新同步')
    parser.add_argument('--json', '-j', action='store_true', help='輸出 JSON 格式')
    parser.add_argument('--show', '-s', action='store_true', help='顯示現有清單統計')

    args = parser.parse_args()

    # 載入現有清單
    existing = load_existing_companies()

    # 顯示現有清單統計
    if args.show:
        if existing:
            print(f"\n=== 現有公司清單 ===")
            print(f"總數: {existing.get('total', 0)} 間")
            print(f"更新時間: {existing.get('fetched_at', 'N/A')}")

            # 統計代碼長度分布
            code_lengths = {}
            for c in existing.get('companies', []):
                length = len(c['code'])
                code_lengths[length] = code_lengths.get(length, 0) + 1

            print(f"\n代碼長度分布:")
            for length, count in sorted(code_lengths.items()):
                print(f"  {length} 位數: {count} 間")
        else:
            print("尚未同步公司清單，請執行: python sync_companies.py")
        return

    # 同步公司清單
    new_data = sync_companies()

    if 'error' in new_data:
        print(f"\n同步失敗: {new_data['error']}")
        return

    print(f"\n同步完成！共取得 {new_data['total']} 間公司")

    # 比較差異
    if existing:
        diff = compare_companies(existing, new_data)

        if diff['added'] or diff['removed']:
            print(f"\n=== 變更報告 ===")
            print(f"舊清單: {diff['old_total']} 間")
            print(f"新清單: {diff['new_total']} 間")

            if diff['added']:
                print(f"\n新增 {len(diff['added'])} 間公司:")
                for c in diff['added'][:10]:
                    print(f"  + {c['code']} {c['name']}")
                if len(diff['added']) > 10:
                    print(f"  ... 還有 {len(diff['added']) - 10} 間")

            if diff['removed']:
                print(f"\n移除 {len(diff['removed'])} 間公司:")
                for c in diff['removed'][:10]:
                    print(f"  - {c['code']} {c['name']}")
                if len(diff['removed']) > 10:
                    print(f"  ... 還有 {len(diff['removed']) - 10} 間")
        else:
            print("\n公司清單無變更")

    # 儲存
    save_path = save_companies(new_data)
    print(f"\n清單已儲存至: {save_path}")

    if args.json:
        print(json.dumps(new_data, ensure_ascii=False, indent=2))

if __name__ == '__main__':
    main()
