#!/usr/bin/env python3
"""
Uzupełnia year_established na podstawie krs_registration_date
dla firm które mają datę KRS ale brak roku założenia.
"""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from dotenv import load_dotenv
load_dotenv()

from database import SessionLocal, Company

def main():
    db = SessionLocal()
    try:
        # Firmy z datą KRS ale bez year_established
        companies = db.query(Company).filter(
            Company.krs_registration_date.isnot(None),
            Company.year_established.is_(None)
        ).all()

        print(f"Znaleziono {len(companies)} firm do uzupełnienia\n")

        for company in companies:
            year = company.krs_registration_date.year
            print(f"  {company.name}: {company.krs_registration_date} -> rok {year}")
            company.year_established = year

        db.commit()
        print(f"\n✅ Uzupełniono rok założenia dla {len(companies)} firm")

    except Exception as e:
        db.rollback()
        print(f"❌ Błąd: {e}")
        raise
    finally:
        db.close()

if __name__ == "__main__":
    main()
