#!/usr/bin/env python3
"""
자재 규격/재질 기준표 테이블 생성 및 데이터 삽입 스크립트
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sqlalchemy import create_engine, text
from app.database import DATABASE_URL

def create_tables():
    """테이블 생성"""
    engine = create_engine(DATABASE_URL)
    
    with engine.connect() as conn:
        print("자재 규격/재질 기준표 테이블 생성 시작...")
        
        # 1. 자재 규격 표준 테이블
        conn.execute(text("""
            CREATE TABLE IF NOT EXISTS material_standards (
                id SERIAL PRIMARY KEY,
                standard_code VARCHAR(20) UNIQUE NOT NULL,
                standard_name VARCHAR(100) NOT NULL,
                description TEXT,
                country VARCHAR(50),
                is_active BOOLEAN DEFAULT TRUE,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
        """))
        print("  - material_standards 테이블 생성됨")
        
        # 2. 제조방식별 카테고리 테이블
        conn.execute(text("""
            CREATE TABLE IF NOT EXISTS material_categories (
                id SERIAL PRIMARY KEY,
                standard_id INTEGER REFERENCES material_standards(id),
                category_code VARCHAR(50) NOT NULL,
                category_name VARCHAR(100) NOT NULL,
                description TEXT,
                is_active BOOLEAN DEFAULT TRUE,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
        """))
        print("  - material_categories 테이블 생성됨")
        
        # 3. 구체적인 규격 테이블
        conn.execute(text("""
            CREATE TABLE IF NOT EXISTS material_specifications (
                id SERIAL PRIMARY KEY,
                category_id INTEGER REFERENCES material_categories(id),
                spec_code VARCHAR(20) NOT NULL,
                spec_name VARCHAR(100) NOT NULL,
                description TEXT,
                material_type VARCHAR(50),
                manufacturing VARCHAR(50),
                pressure_rating VARCHAR(100),
                is_active BOOLEAN DEFAULT TRUE,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
        """))
        print("  - material_specifications 테이블 생성됨")
        
        # 4. 등급별 상세 정보 테이블
        conn.execute(text("""
            CREATE TABLE IF NOT EXISTS material_grades (
                id SERIAL PRIMARY KEY,
                specification_id INTEGER REFERENCES material_specifications(id),
                grade_code VARCHAR(20) NOT NULL,
                grade_name VARCHAR(100),
                composition VARCHAR(200),
                applications VARCHAR(200),
                temp_max VARCHAR(50),
                temp_range VARCHAR(100),
                yield_strength VARCHAR(50),
                tensile_strength VARCHAR(50),
                corrosion_resistance VARCHAR(50),
                stabilizer VARCHAR(50),
                base_grade VARCHAR(20),
                is_active BOOLEAN DEFAULT TRUE,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
        """))
        print("  - material_grades 테이블 생성됨")
        
        # 5. 정규식 패턴 테이블
        conn.execute(text("""
            CREATE TABLE IF NOT EXISTS material_patterns (
                id SERIAL PRIMARY KEY,
                specification_id INTEGER REFERENCES material_specifications(id),
                pattern TEXT NOT NULL,
                description VARCHAR(200),
                priority INTEGER DEFAULT 1,
                is_active BOOLEAN DEFAULT TRUE,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
        """))
        print("  - material_patterns 테이블 생성됨")
        
        # 6. 특수 재질 테이블
        conn.execute(text("""
            CREATE TABLE IF NOT EXISTS special_materials (
                id SERIAL PRIMARY KEY,
                material_type VARCHAR(50) NOT NULL,
                material_name VARCHAR(100) NOT NULL,
                description TEXT,
                composition VARCHAR(200),
                applications TEXT,
                temp_max VARCHAR(50),
                manufacturing VARCHAR(50),
                is_active BOOLEAN DEFAULT TRUE,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
        """))
        print("  - special_materials 테이블 생성됨")
        
        # 7. 특수 재질 등급 테이블
        conn.execute(text("""
            CREATE TABLE IF NOT EXISTS special_material_grades (
                id SERIAL PRIMARY KEY,
                material_id INTEGER REFERENCES special_materials(id),
                grade_code VARCHAR(20) NOT NULL,
                composition VARCHAR(200),
                applications VARCHAR(200),
                temp_max VARCHAR(50),
                strength VARCHAR(50),
                purity VARCHAR(100),
                corrosion VARCHAR(50),
                is_active BOOLEAN DEFAULT TRUE,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
        """))
        print("  - special_material_grades 테이블 생성됨")
        
        # 8. 특수 재질 정규식 패턴 테이블
        conn.execute(text("""
            CREATE TABLE IF NOT EXISTS special_material_patterns (
                id SERIAL PRIMARY KEY,
                material_id INTEGER REFERENCES special_materials(id),
                pattern TEXT NOT NULL,
                description VARCHAR(200),
                priority INTEGER DEFAULT 1,
                is_active BOOLEAN DEFAULT TRUE,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
        """))
        print("  - special_material_patterns 테이블 생성됨")
        
        # 인덱스 생성
        conn.execute(text("CREATE INDEX IF NOT EXISTS idx_material_standards_code ON material_standards(standard_code);"))
        conn.execute(text("CREATE INDEX IF NOT EXISTS idx_material_categories_standard ON material_categories(standard_id);"))
        conn.execute(text("CREATE INDEX IF NOT EXISTS idx_material_specifications_category ON material_specifications(category_id);"))
        conn.execute(text("CREATE INDEX IF NOT EXISTS idx_material_grades_specification ON material_grades(specification_id);"))
        conn.execute(text("CREATE INDEX IF NOT EXISTS idx_material_patterns_specification ON material_patterns(specification_id);"))
        conn.execute(text("CREATE INDEX IF NOT EXISTS idx_special_materials_type ON special_materials(material_type);"))
        conn.execute(text("CREATE INDEX IF NOT EXISTS idx_special_material_grades_material ON special_material_grades(material_id);"))
        conn.execute(text("CREATE INDEX IF NOT EXISTS idx_special_material_patterns_material ON special_material_patterns(material_id);"))
        
        # 활성 상태 인덱스
        conn.execute(text("CREATE INDEX IF NOT EXISTS idx_material_standards_active ON material_standards(is_active);"))
        conn.execute(text("CREATE INDEX IF NOT EXISTS idx_material_categories_active ON material_categories(is_active);"))
        conn.execute(text("CREATE INDEX IF NOT EXISTS idx_material_specifications_active ON material_specifications(is_active);"))
        conn.execute(text("CREATE INDEX IF NOT EXISTS idx_material_grades_active ON material_grades(is_active);"))
        conn.execute(text("CREATE INDEX IF NOT EXISTS idx_material_patterns_active ON material_patterns(is_active);"))
        conn.execute(text("CREATE INDEX IF NOT EXISTS idx_special_materials_active ON special_materials(is_active);"))
        conn.execute(text("CREATE INDEX IF NOT EXISTS idx_special_material_grades_active ON special_material_grades(is_active);"))
        conn.execute(text("CREATE INDEX IF NOT EXISTS idx_special_material_patterns_active ON special_material_patterns(is_active);"))
        
        conn.commit()
        print("모든 테이블 및 인덱스 생성 완료!")

def main():
    """메인 실행 함수"""
    print("자재 규격/재질 기준표 DB 마이그레이션 시작")
    print("=" * 50)
    
    create_tables()
    
    print("\n" + "=" * 50)
    print("마이그레이션 완료!")
    print("\n다음 단계: python scripts/06_insert_material_standards_data.py")

if __name__ == "__main__":
    main() 