import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[4] / 'base_platform'))
from sqlalchemy import text
from app.db.session import SessionLocal
from app.models import role, role_permission, user, tenant, knowledge_base

def init_tax_knowledge_base(tenant_id: int, user_id: int=None):
    from app.models.knowledge_base import KnowledgeBase
    db = SessionLocal()
    try:
        db.execute(text(f'SET search_path TO tenant_{tenant_id}, public'))
        knowledge_bases = [{'name': '税法法规', 'description': '税收法律法规文件', 'type': 'tax_regulations', 'icon': '📜'}, {'name': '实务案例', 'description': '税务实务案例分析', 'type': 'tax_cases', 'icon': '📋'}, {'name': 'SOP', 'description': '税务标准作业程序', 'type': 'tax_sop', 'icon': '📝'}]
        kb_ids = []
        for kb_data in knowledge_bases:
            existing = db.query(KnowledgeBase).filter_by(type=kb_data['type'], tenant_id=tenant_id).first()
            if existing:
                print(f'  - KB exists: {existing.name}')
                kb_ids.append(existing.id)
                continue
            kb = KnowledgeBase(**kb_data, code='BAAI/bge-m3', tenant_id=tenant_id, created_by=user_id)
            db.add(kb)
            db.flush()
            kb_ids.append(kb.id)
            print(f'  ✓ Created KB: {kb.name} (ID: {kb.id})')
        db.commit()
        return kb_ids
    except Exception as e:
        db.rollback()
        print(f'  ✗ Failed to create tax KBs: {e}')
        raise
    finally:
        db.close()